假设以下路由设置:
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'),
)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,有两种主要布局,普通页面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;
Run Code Online (Sandbox Code Playgroud)
现在,该布局在顶部有一个标题部分,需要根据我们在应用程序中的位置显示文本。
由于我是 React JS 的新手,我不想只查找“如何从路由器传递 props”或类似内容 - 相反,我感兴趣的是执行此操作的正确方法可能是什么。如果你愿意的话,“反应方式”。无论是涉及直接从路线传递道具,还是更改某种全局状态以影响标题,或者处理这种情况的“正确”方法是什么。
编辑:我应该提到我正在使用 React JS v.15.6.1 和 React-router v.3.0.5。
如果我理解正确的话,您想要实现的目标是动态获取您所在的组件/页面的名称。
如果是这种情况,您可以添加一个名为name路由的 prop 并在组件内获取它。
例如:
<Route path="/" name="App" component={App}>
<IndexRoute name="Home Page" component={HomePage} />
<Route path="/home" name="Home Page" component={HomePage} />
<Route path="/about" name="About Page" component={AboutPage} />
<Route path="*" component={NotFoundPage} />
</Route>
Run Code Online (Sandbox Code Playgroud)
在组件内部,这是获取名称的方法:
render() {
// ...
const currentRouteName = this.props.routes[this.props.routes.length - 1].name;
// ... rest of code
Run Code Online (Sandbox Code Playgroud)