gpt4 book ai didi

javascript - 在 react-router v4 中使用 React IndexRoute

转载 作者:IT老高 更新时间:2023-10-28 21:54:11 26 4
gpt4 key购买 nike

我正在通过在线教程学习 React 自己。

所以这是一个关于使用 React Router 的基本示例:

<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/home" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/contact" component={Contact}/>
</Route>
</Router>

使用我的 App 组件:

class App extends React.Component {
render() {
return (
<div>
<ul>
<li><Link to="home">Home</Link></li>
<li><Link to="about">About</Link></li>
<li><Link to="contact">Contact</Link></li>
</ul>
{this.props.children}
</div>
)
}
}
export default App;

但是,我在使用 IndexRoute 时遇到问题,因为它什么都没有显示,所以我在 npm 上搜索 react-router-dom v4 的模块,里面没有 IndexRoute。相反,它使用这个:

<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/contact" component={Contact}/>
</div>
</Router>

那么如何为 1 个路径渲染 2 个组件?

最佳答案

更新react-router-4 已经改变,它不再有子 Node 。但是,使用 Route 组件,您可以渲染与路径匹配的任何内容。

<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
<hr/>

// All 3 components below would be rendered when in a homepage
<Route exact path="/" component={Home}/>
<Route exact path="/" component={About}/>
<Route exact path="/" component={Contact}/>

<Route path="/about" component={About}/>
<Route path="/contact" component={Contact}/>
</div>
</Router>

这意味着如果你想要一个包装器,你可以把它写在组件里面。

关于javascript - 在 react-router v4 中使用 React IndexRoute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42748727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com