【问题标题】:React 15.1.0, Pass entire state from parent to childReact 15.1.0,将整个状态从父级传递给子级
【发布时间】:2016-09-26 18:57:29
【问题描述】:

我正在使用 React 15.1.0

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

在旧版本的 react 中,当我想将整个状态传递给 child 时,我们使用 {...this.state} 然后我们使用来自 child 的 {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>
        );
    }
});

在子组件中,我正在尝试使用以下代码。

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

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

【问题讨论】:

  • 我不明白这个问题.. {...this.state} 有什么问题?
  • 它在最新的 React 版本中不起作用。
  • 它适用于我webpackbin.com/Nk_ES2MQW 所以.. 在你上面的例子中(不使用 JSX)这不是一个特定的反应语法。你需要 stage-2 rest/spread 属性 babel 预设
  • 它与 React 无关,它是 ES6 特性。
  • 你就不能React.cloneElement(this.props.children, this.state)吗?

标签: javascript reactjs ecmascript-6 react-router


【解决方案1】:
{...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"}

【讨论】:

    【解决方案2】:

    我只是改了下面的代码sn-p,

    Speaker: {this.props.title}
    

    在子组件中,瞧!!!代码有效。谢谢大家。

    下面是截图。

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 2019-03-07
      • 2021-04-25
      • 2016-05-13
      • 1970-01-01
      相关资源
      最近更新 更多