【问题标题】:declare component to all routes react-router向所有路由声明组件 react-router
【发布时间】:2018-12-04 23:22:34
【问题描述】:

我有一个标题,在它里面我有链接组件来导航任何页面,并且标题需要在所有路由上显示,我将标题组件放在 switch 方法中,因为我里面有组件。但是header组件是单独渲染的,其他组件不渲染,只有header组件。

class App extends Component {
    render() {
        return (
            <div>
                <BrowserRouter>
                    <Switch>
                        <Header/>
                        <Route path={'/'} exact={true} component={Main}/>
                        <Route path={'/cursos'} exact={true} component={Cursos}/>
                        <Route path={'/forum'} exact={true} component={Forum}/>
                        <Route path={'/login'} exact={true} component={Login}/>
                    </Switch>
                </BrowserRouter>
                <Footer/>
            </div>
        );
    }
} 

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    试试这样的:

    class App extends Component {
        render() {
            return (
                <div>
                    <BrowserRouter>
                      <React.Fragment>
                        <Header/>
                        <Switch>                        
                            <Route path={'/'} exact={true} component={Main}/>
                            <Route path={'/cursos'} exact={true} component={Cursos}/>
                            <Route path={'/forum'} exact={true} component={Forum}/>
                            <Route path={'/login'} exact={true} component={Login}/>
                        </Switch>
                      </React.Fragment>
                    </BrowserRouter>
                    <Footer/>
                </div>
            );
        }
    } 

    Switch 旨在仅渲染一个孩子(匹配的第一个)。

    【讨论】:

    • 它的作品,我会进一步研究React.Fragment,非常感谢
    猜你喜欢
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 2016-07-05
    • 1970-01-01
    • 2019-08-26
    • 2023-02-25
    相关资源
    最近更新 更多