来自另一个组件的 React-Router-4 路由 [英] React-Router-4 routing from another component
问题描述
是否可以从另一个组件路由一个组件?
所以通常会像下面那样做
link <NavLink to="/anotherLink">link </NavLink><开关><路由精确路径="/link" component={linkComponent}/><Route path="/anotherLink" component={anotherLinkComponent}/></开关>
但是是否可以将 NavLink 放在一个加载到主组件中的组件中,然后从主组件路由?所以在一个组件中有 NavLink
并且在主组件中有 Route
.
导航组件
export default class Nav extends Component {使成为() {返回 (<nav className="导航"><ul className="nav-container"><li><NavLink to="/" className="nav-title">第一页</NavLink><li><NavLink to="second-page" className="nav-title">第二页</NavLink><li><NavLink to="third-page" className="nav-title">第三页</NavLink><div className="导航装饰">
</nav>)}}
应用组件
从'whateverthepath'导入导航;导出默认类 App 扩展组件 {使成为() {返回 (<div><导航/><开关><路由精确路径="/" component={Firstpage}/><Route path="/secondpage" component={Secondpage}/></开关>
)}}
所有适当的 React 导入都已完成
这绝对是可能的,您的示例甚至应该可以正常工作.您需要确保的最重要的事情是您的
被渲染为某个点.您的示例工作的原因是因为您在与
语句相同的 render() 方法中呈现 .如果你只是渲染
而不渲染 switch 语句,那么 NavLinks 会把你带到 React Router 没有被告知的地方.这通常就是为什么你的
几乎总是在你最父组件中,以确保它们被呈现.
Is it possible to route a component from another component?
So normally it would be done like below
<NavLink to="/link">link</NavLink>
<NavLink to="/anotherLink">link </NavLink>
<Switch>
<Route exact path="/link" component={linkComponent}/>
<Route path="/anotherLink" component={anotherLinkComponent}/>
</Switch>
but is it possible to have NavLink in one component which is loaded in the main component then route from the main component? So have NavLink
in one component and have Route
in the main component.
The Nav component
export default class Nav extends Component {
render() {
return (
<nav className="navigation">
<ul className="nav-container">
<li>
<NavLink to="/" className="nav-title">
First Page
</NavLink>
</li>
<li>
<NavLink to="second-page" className="nav-title">
Second Page
</NavLink>
</li>
<li>
<NavLink to="third-page" className="nav-title">
Third Page
</NavLink>
</li>
</ul>
<div className="nav-decoration">
</div>
</nav>
)
}
}
The App component
import Nav from 'whateverthepath';
export default class App extends Component {
render() {
return (
<div>
<Nav/>
<Switch>
<Route exact path="/" component={Firstpage}/>
<Route path="/secondpage" component={Secondpage}/>
</Switch>
</div>
)
}
}
All the appropriate React imports are done
That's definitely possible and your example should even work as is. The biggest thing you'll need to make sure of is that your <Route>
s were rendered as some point. The reason your example works is because you're rendering <Nav>
in the same render() method as your <Switch>
statement. If you were to instead just render <Nav>
without ever rendering the switch statement, then the NavLinks would take you somewhere that React Router hasn't been informed about. That's typically why your <Route>
s are almost always in your most parent component, to make sure they're rendered.
这篇关于来自另一个组件的 React-Router-4 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!