React 15.1.0,将整个状态从父级传递给子级

时间:2016-05-28 14:45:42

标签: javascript reactjs ecmascript-6 react-router

我使用的是React 15.1.0

假设有父母" P"组件,它包含一个子组件" C"。

在旧版本的反应中,当我想将整个州传递给孩子时,我们使用了 {... this.state} 然后我们使用了来自孩子的{this.props.something}成分

上述实例的最新最新React 15.1.0中是否有一种简单的方法?

注意:我需要传递整个状态,而不是个别道具。

 <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>
        );
    }
});

在Child Component中我正在尝试使用下面的代码。

var Speaker = React.createClass({
    render() {
        return (
            <h1>Speaker: {this.state.title}</h1>
        );
    }
});

但是在Chrome浏览器中,我得到了以下结果;

enter image description here

2 个答案:

答案 0 :(得分:2)

{...this.state}

等于

this.state

在这种情况下。 ES6中的Spread运算符(不是React特定的功能)...扩展了一个对象&#39;属性到父对象中,参见:

let sampleObject = {
  name: 'a_name'
};

console.log('Non-spread', sampleObject);  // Non-spread {name: "a_name"}
console.log('Spread', {... sampleObject});  // Spread {name: "a_name"}

答案 1 :(得分:0)

我刚刚更改了以下代码段,

Speaker: {this.props.title}

在儿童组件中瞧!!!代码工作。谢谢大家。

以下是快照。 enter image description here

相关问题