我是第一次使用React-router,但现在还不知道如何思考。这是我在嵌套路由中加载组件的方式。
入口点.js
ReactDOM.render( <Router history={hashHistory} > <Route path="/" component={App}> <Route path="models" component={Content}> </Route> </Router>, document.getElementById('app') );
App.js
render: function() { return ( <div> <Header /> {this.props.children} </div> ); }
因此,我的App的子级是我发送的内容组件。我使用的是Flux,我的App.js具有状态并侦听更改,但是我不知道如何将该状态传递给this.props.children 。在使用react-router之前,我的App.js显式定义了所有子级,因此传递状态是自然的,但我现在不知道如何做。
这个问题归结为, 您如何将道具传递给孩子?
当今的技术:
react-router-dom
假设一些有状态组件:
import React from 'react' import { BrowserRouter, Route } from 'react-router-dom' // some component you made import Title from './Title' class App extends React.Component { // this.state state = { title: 'foo' } // this.render render() { return ( <BrowserRouter> // when the url is `/test` run this Route's render function: <Route path="/:foobar" render={ // argument is props passed from `<Route /`> routeProps => // render Title component <Title // pass this.state values title={this.state.title} // pass routeProps values (url stuff) page={routeProps.match.params.foobar} // "test" /> } /> </BrowserRouter> ) } }
这是有效的,因为 this.props.children 是一个函数:
// "smart" component aka "container" class App extends React.Component { state = { foo: 'bar' } render() { return this.props.children(this.state.foo) } } // "dumb" component aka "presentational" const Title = () => ( <App> {title => <h1>{title}</h1>} </App> )
在codesandbox上的例子
使用几个React帮助器方法,您可以添加状态,道具等 this.props.children
this.props.children
render: function() { var children = React.Children.map(this.props.children, function (child) { return React.cloneElement(child, { foo: this.state.foo }) }) return <div>{children}</div> }
然后,您的子组件可以通过props访问它this.props.foo。
this.props.foo