我有这样的路线:
<Provider store={store}>
<BrowserRouter>
<Route path="/" component={App} />
<Route path="/customers" component={Customers} />
<Route path="/tickets" component={Tickets} />
</BrowserRouter>
</Provider>
当路由为
/customers
我要 Customers
组件 内 App
成分。当路由为/tickets
我要 Tickets
内 App
而不是 Customers
.我可以检查路线使用this.props.location.pathname == '/customers'
但这就是路由器的用途,对吗?我不应该检查路线和渲染。根据我上面的路线,我看到
Customers
组件 下面 App
而不是里面。App
由标题和东西组成。我不想为我的所有组件添加 header 代码。应用程序.js:
<Header style={{ height: '39px', lineHeight: '39px' }}>
<Link to="/home">
<div className="logo" style={{ float: 'left' }}>
<img src="" />
<h2>Appnam</h2>
</div>
</Link>
{navEl}
</Header>
<Content >
// Customer or Tickets component here based on route
</Content>
如何渲染内部组件
App
根据路线。
最佳答案
假设你有 App 作为主要组件,并且你想要 App 组件中的 Tickets 和 Customers 组件,你可以使用嵌套路由
<Provider store={store}>
<BrowserRouter>
<Route path="/" component={App} />
</BrowserRouter>
</Provider>
内部应用组件
class App extends React.Component {
render() {
return (
<div>
{/* rest of App code */}
<Route path="/customers" component={Customers} />
<Route path="/tickets" component={Tickets} />
</div>
)
}
}
关于javascript - 如何基于路由在组件内部渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61094353/