【发布时间】: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