请多多包涵.我只是学习Reactjs并且坚持到了某一点.
APP-client.js
ReactDOM.render((
<Router history={hashHistory}>
<Route path="/" component={APP}>
<IndexRoute component={Audience}/>
<Route path="speaker" component={Speaker}/>
<Route path="board" component={Board}/>
</Route>
</Router>
), document.getElementById('react-container'));
APP.js
var APP = React.createClass({
getInitialState() {
return {
status: 'disconnected',
title: ''
}
},
emit(eventName, payload) {
this.socket.emit(eventName, payload);
},
render() {
return (
<div>
<Header title={this.state.title} status={this.state.status}/>
{this.props.children}
</div>
);
}
});
Audience.js:
var Audience = React.createClass({
render() {
return (<h1>Audience: {this.props.title}</h1>);
}
});
该页面显示所有组件,但this.props.title未显示在页面中,并且emit()未触发.如何将道具传递给APP上的{this.props.children}(即观众或演讲者)?
更新:
APP.js render():
render() {
const _this = this;
return (
<div>
<Header title={this.state.title} status={this.state.status}/>
{ React.children.map(this.props.children, (child, index) => {
//Get props of child
// const childProps = child.props;
//do whatever else you need, create some new props, change existing ones
//store them in variables
return React.cloneElement(child, {
// ...childProps, //these are the old props if you don't want them changed
// ...someNewProps,
// someOldPropOverwritten, //overwrite some old the old props
..._this.state,
emit: _this.emit
});
})
}
</div>
);
}
});
最佳答案 React为您提供了一系列API,它们将完全解决您不确定如何实现的问题(将道具传递给this.props.children呈现的组件的方法)
首先,你需要看看cloneElement
它基本上会采用一个React元素,克隆它,并返回另一个带有道具,你可以根据自己的需要完全改变,改变或替换.
此外,将它与Children Utilities相结合 – 循环通过提供给顶层组件的子项,并对每个元素进行必要的更改.
您可以找到一个更全面的答案,我在下面提到的一个问题的非常相似的主题上提供了答案:
changing-components-based-on-url-with-react-router
基本上,有些东西:
render() {
const _this = this;
return (
{React.Children.map(this.props.children, (child, index) => {
//Get props of child
const childProps = child.props;
//do whatever else you need, create some new props, change existing ones
//store them in variables
return React.cloneElement(child, {
...childProps, //these are the old props if you don't want them changed
...someNewProps,
someOldPropOverwritten, //overwrite some old the old props
..._this.state,
someFn: _this.someFn,
...
});
)}
}