我在主组件中定义了一个路由器。我想通过react路由器在此主要组件中渲染组件。每次渲染任何路线时,我都希望在顶部也具有主组件,即导航栏。我该如何路由?
方法1:
import React, { Component } from 'react';
import './App.css';
import { Provider } from 'react-redux';
import store from './store';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Main from './actions/sidebartoggleActions'
import FirstDashboard from './_layouts/views/firstDashboard';
import SecondDashboard from './_layouts/views/secondDashboard';
import ThirdDashboard from './_layouts/views/thirdDashboard';
import FourthDashboard from './_layouts/views/fourthDashboard';
class Main extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div>
<Route path='/' exact strict component={Main} />
<Route path='/overview1' exact strict component={FirstDashboard} />
<Route path='/overview2' exact strict component={SecondDashboard} />
<Route path='/overview3' exact strict component={ThirdDashboard} />
<Route path='/overview4' exact strict component={FourthDashboard} />
</div>
</Router>
</Provider>
);
}
}
export default Main;
方法2:
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import store from './store';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import App from './actions/sidebartoggleActions'
import FirstDashboard from './_layouts/views/firstDashboard';
import SecondDashboard from './_layouts/views/secondDashboard';
import ThirdDashboard from './_layouts/views/thirdDashboard';
import FourthDashboard from './_layouts/views/fourthDashboard';
class Main extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div>
<App />
<Route path='/overview1' exact strict component={FirstDashboard} />
<Route path='/overview2' exact strict component={SecondDashboard} />
<Route path='/overview3' exact strict component={ThirdDashboard} />
<Route path='/overview4' exact strict component={FourthDashboard} />
</div>
</Router>
</Provider>
);
}
}
export default Main;
我找到了解决方案,将路线嵌套在组件中,然后在Index组件中调用{props.this.children},解决了我的问题。我引用了-https: //github.com/reactjs/react-router-tutorial/tree/master/lessons/04-nested-routes
const Main = () => (
<Provider store={store}>
<Router>
<Switch>
<Index>
<Route path='/overview1' component={FirstDashboard} />
<Route path='/overview2' component={SecondDashboard} />
<Route path='/overview3' component={ThirdDashboard} />
<Route path='/overview4' component={FourthDashboard} />
</Index>
</Switch>
</Router>
</Provider>
)
export default Main;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句