这个问题归结为, 您如何将道具传递给孩子?
2018年6月答案
当今的技术:
- 反应16+
- 反应路由器4:
react-router-dom
- 来自官方文档的渲染道具
假设一些有状态组件:
import React from 'react'import { BrowserRouter, Route } from 'react-router-dom'// some component you madeimport 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>)在presandbox上的例子
我以前不再推荐的老式答案:
使用几个React帮助器方法,您可以添加状态,道具等
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。



