我在react-router 3中设置了一个适用于嵌套组件的设置。现在当我尝试在反应路由器V4中做同样的事情时,我似乎无法让它发挥作用。 我已经阅读了一些文章,包括文档,但仍然无法使其发挥作用。我首先在react-router 3中发布我的设置然后在那之后我尝试了react-router 4
React Router 3 Setup 的 App.js
import { Router, browserHistory } from 'react-router';
import Store from './store';
import routes from './routes';
ReactDOM.render(
<Provider store={Store}>
<Router history={browserHistory} routes={routes}/>
</Provider>
,document.querySelector('#react-container'));
routes.js
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import MainLayout from './layouts/main';
import NotFound from './pages/notfound';
import Home from './pages/home';
export default (
<Route path="/" component={MainLayout}>
<IndexRoute component={Home}/>
<Route path="*" component={NotFound} />
</Route>
);
布局/ main.js
import React, { Component } from 'react';
import Header from '../components/header';
import Footer from '../components/footer';
export default class MainLayout extends Component{
render(){
return (
<div>
<Header />
<div id="page-content">{this.props.children}</div>
<Footer />
</div>
);
}
};
React-router 4 我试图弄清楚如何使用我的layout.js嵌套,就像我在React Router 3中所做的那样
App.js
import { BrowserRouter as Router } from 'react-router-dom';
import Store from './store';
import routes from './routes';
ReactDOM.render(
<Provider store={Store}>
<Router routes={routes}/>
</Provider>
,document.querySelector('#react-container'));
routes.js
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import MainLayout from './layouts/main';
import NotFound from './pages/notfound';
import Home from './pages/home';
export default (
// <Route path="/" component={MainLayout}>
// <IndexRoute component={Home}/>
// <Route path="*" component={NotFound} />
// </Route>
<Switch>
<Route exact path="/" component={MainLayout}/>
<Route path="/" component={Home}/>
<Route component={NotFound} />
</Switch>
);
答案 0 :(得分:0)
如果MainLayout将成为所有部分(Home等)的容器(布局),那么您可以将MainLayout的子路由放在MainLayout中:
import React, { Component } from 'react';
import Header from '../components/header';
import Footer from '../components/footer';
const Main = ({match}) => {
render() {
return (
<div>
<Header />
<div id="page-content">
<Route path={match.url + '/home'} component={Home} />
<Route path={match.url + '/about'} component={About} />
</div>
<Footer />
</div>
);
}
}
export default Main
如果您使用MainLayout有多个部分,则可以创建所有路径及其相关组件的数组,并通过它们map
创建。