我正在尝试将一个值从渲染函数传递给组件:
= react_component('App', props: {test: 'abc'}, prerender: false)
路线.jsx
<Route path="/" component={App} >
App.jsx (component(
class App extends React.Component {
render() {
return (
<Header test={this.props.test}>
</Header>
{this.props.children}
<Footer />
);
}
}
App.propTypes = { test: PropTypes.string };
对于这个完整的流程,似乎没有一个连贯的答案。
我尝试了以下方法:
<Route path="/" component={() => (<App myProp="value" />)}/>
但这仍然没有回答获取初始渲染调用(react_component(提供的值的问题
寻找有关如何从 "查看"到"反应路由器"到"组件">
我们将从以下观点开始:
<%= react_component('MyRoute', {test: 123}, prerender: false) %>
现在我们将创建一个保存我们route
的组件:
class MyRoute extends Component{
constructor(props){
super(props)
}
render(){
return(
<Switch>
<Route path="/" render={() => <App test={this.props.test} />} />
<Route path="/login" component={Login} />
</Switch>
)
}
}
如您所见,我们将 test
道具从 Route
组件传递到App
组件。现在我们可以在App
组件中使用 test
道具:
class App extends Component{
constructor(props){
super(props)
}
render(){
return(
<h1>{this.props.test}</h1>
)
}
}
<Route path="/" render={attr => <App {...attr} test="abc" />} />
在路由器 v3 中,你会做这样的事情
像这样将您的应用程序组件包装在 withRouter 下
import { withRouter } from 'react-router';
class App extends React.Component {
render() {
return (
<Header test={this.props.test}>
</Header>
{
this.props.children &&
React.clone(this.props.children, {...this.props} )}
<Footer />
);
}
}
App.propTypes = { test: PropTypes.string };
export const APP = withRouter(App);
并像这样构建您的路线...
<Route path="/" component={APP}>
<Route path="/lobby" component={Lobby} />
<Route path="/map" component={GameMap} />
...
</Route>
因此,您的子路由将在 APP 子属性中呈现,并且道具将传递给它们。
希望这有帮助!