如何在React Router V4中实现嵌套路由(子路由)? [英] How to implement nested Routing (child routes) in react router v4?
本文介绍了如何在React Router V4中实现嵌套路由(子路由)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要的组件树如下 - 登录 - 家 - 接触 -关于
The component tree i want is as below - Login - Home - Contact - About
Contact和About是Home的子代. 这是我的App.js
Contact and About are children of Home. This is my App.js ,
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Route exact path="/home" component={HomeView} />
</div>
</BrowserRouter>
);
}
}
render(<App />, document.getElementById('root'));
这是家,
export const HomeView = ({match}) => {
return(
<div>
<NavBar />
Here i want to render the contact component, (Navbar need to stay)
</div>
)
}
这是我的导航栏,
export const NavBar = () => {
return (
<div>
<Link to="/home">Home</Link>
<Link to="/home/contact">Contact</Link>
<hr/>
</div>
)
}
Contact组件只需要呈现你好文本".
Contact component just need to render "hello text".
推荐答案
要创建嵌套路由,您需要删除exact
:
To make nested routes you need to remove exact
:
<Route path="/home" component={HomeRouter} />
并添加一些路线:
export const HomeRouter = ({match}) => {
return(
<div>
<NavBar />
{/* match.path should be equal to '/home' */}
<Switch>
<Route exact path={match.path} component={HomeView} />
<Route exact path={match.path + '/contact'} component={HomeContact} />
<Switch>
</div>
)
}
您不需要在嵌套路由中使用match.path
,但是这样一来,如果您决定更改路由,则将所有内容从"/home"移动到"/new/home"将更加容易.
You don't need use match.path
in nested routes but this way it will be easier to move everything from "/home" to "/new/home" in case you decide to change your routing.
这篇关于如何在React Router V4中实现嵌套路由(子路由)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文