[英]React 15.1.0, Pass entire state from parent to child
我正在使用React 15.1.0 。
假設有父“P”組件,它包含子組件“C”。
在舊版本的react中,當我想將整個狀態傳遞給child時,我們使用了{... 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>
在Parent組件中,我有以下代碼;
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瀏覽器中,我得到了以下結果;
{...this.state}
等於
this.state
在這種情況下。 ES6中的Spread運算符(不是特定於React的特性) ...
將一個對象的屬性擴展為父對象,請參閱:
let sampleObject = {
name: 'a_name'
};
console.log('Non-spread', sampleObject); // Non-spread {name: "a_name"}
console.log('Spread', {... sampleObject}); // Spread {name: "a_name"}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.