gpt4 book ai didi

reactjs - 如何将 Prop 传递给 react-router 中使用的布局?

转载 作者:行者123 更新时间:2023-12-04 13:46:36 24 4
gpt4 key购买 nike

假设以下路由设置:

ReactDOM.render(  
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/">
<Route component={Layout} onEnter={checkIndexAuthorization(store)}>
<IndexRoute component={Home} />
<Route path="/home" component={Home} />
</Route>

<Route component={AuthLayout} onEnter={checkLoginAuthorization(store)}>
<Route path="/login" component={Login} />
</Route>
</Route>
</Router>
</Provider>,
document.getElementById('root'),
)

如您所见,有两种主要布局,普通 Layout和登录页面 AuthLayout .正常布局用于应用程序本身。

下面,您可以看到 Layout组件文件:
//========================================
// IMPORTS
//========================================

import React, { PropTypes } from 'react';

//========================================
// COMPONENT
//========================================

const Layout = props => (
<main className="app">
<header>
{props.sectionTitle}
</header>

<section>
{props.children}
</section>

<footer>

</footer>
</main>
)

Layout.propTypes = {
children: PropTypes.node,
sectionTitle: PropTypes.string // <-- not being set anywhere currently
}

//========================================
// EXPORTS
//========================================

export default Layout;

现在,该布局在顶部有一个标题部分,需要根据我们在应用程序中的位置显示文本。

由于我是 React JS 的新手,我不想只查找“如何从路由器传递 Prop ”或类似内容 - 相反,我感兴趣的是正确的方法可能是什么。 ' react 方式',如果你愿意的话。这是否涉及直接从路线传递 Prop ,或更改某种全局状态以影响标题,或者处理这种情况的“正确”方式是什么。

编辑:我应该提到我使用的是 React JS v. 15.6.1 和 react-router v. 3.0.5。

最佳答案

我也只是在看这个 - 在我的应用程序中,我有私有(private)路由,只有在身份验证后才可用,我看了大约 5 分钟后才想起!

如果您在应用程序中创建私有(private)路由,请不要忘记将 props 传递给新创建的路由组件,例如:

<PrivateRoute path="/path/to/route" name={'Route name'} component={RouteComponent} layout={SimpleLayout} />

以及 PrivateRoute 的定义:
const PrivateRoute = ({ layout: Layout, component: Component, ...rest }) => (
<Route {...rest} render={props => {
const newComponent = Layout ?
<Layout><Component {...rest} {...props} /></Layout>
:
<Component {...props} />;

return Auth.isUserAuthenticated() ? (
newComponent
) : (
<Redirect to={{pathname: '/login', state: { from: props.location }}} />
)
}}/>
);

重要的部分是记住将当前的 props 传播到新的 Component {...rest} 上。

然后在实际的布局文件(例如上面的 SimpleLayout)中,您可以通过以下方式访问 Prop :
this.props.children.props.name

我确信还有更好的方法可以做到这一点,但从我迄今为止的经验来看,这对我来说还不错!

关于reactjs - 如何将 Prop 传递给 react-router 中使用的布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46179774/

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