我正在使用 React 15.1.0。
假设有一个父组件“P”,它包含一个子组件“C”。
在旧版本的 React 中,当我想将整个状态传递给 child 时,我们使用 {...this.state} 然后我们使用来自 child 的 {this.props.something}组件。
在最新的 Latest React 15.1.0 中是否有针对上述实例的简单方法?
注意:我需要传递整个状态而不是单个 Prop 。
<div>
{React.cloneElement(this.props.children, { title: this.state.title })}
</div>
我期待的是像下面这样的东西;
<div>
{React.cloneElement(this.props.children, {...this.state})}
</div>
在父组件中,我有以下代码;
var App = React.createClass({
getInitialState() {
return{
status: 'disconnected',
title: 'Hello World'
}
},
render() {
return(
<div>
<Header title={this.state.title} />
<div>
{React.cloneElement(this.props.children, this.state)}
</div>
</div>
);
}
});
在子组件中,我正在尝试使用以下代码。
var Speaker = React.createClass({
render() {
return (
<h1>Speaker: {this.state.title}</h1>
);
}
});
但在 Chrome 浏览器中,我得到以下结果;
最佳答案
{...this.state}
等于
this.state
在这种情况下。
ES6 中的扩展运算符(不是 React 特定的功能)...
将一个对象的属性扩展到父对象中,请参阅:
let sampleObject = {
name: 'a_name'
};
console.log('Non-spread', sampleObject); // Non-spread {name: "a_name"}
console.log('Spread', {... sampleObject}); // Spread {name: "a_name"}
关于javascript - React 15.1.0,将整个状态从 parent 传递给 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37500361/