我第一次使用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>
);
}
所以我的应用程序的子组件是我发送的内容组件。我正在使用 Flux,我的 App.js 具有状态并监听更改,但我不知道如何将该状态传递给此组件。 Prop .children.在使用react-router之前,我的App.js明确定义了所有子级,因此传递状态是很自然的,但我现在不知道如何做到这一点。
最佳答案
这个问题归结为,如何将 Prop 传递给 child ?
2018 年 6 月答案
当今的技术:
- react 16+
- React Router 4 :
react-router-dom
- Render Props from official docs
假设有一些有状态组件:
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>
)
我之前的老派答案,我不再推荐:
使用几个 React 辅助方法,您可以向 this.props.children
添加状态、 Prop 和其他任何内容
render: function() {
var children = React.Children.map(this.props.children, function (child) {
return React.cloneElement(child, {
foo: this.state.foo
})
})
return <div>{children}</div>
}
然后您的子组件可以通过 Prop this.props.foo
访问它。
关于reactjs - React router 和 this.props.children - 如何将状态传递给 this.props.children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35835670/