[英]ReactJS - updating components when separate class property is changed
在我的项目中,我有一个带有一些反应代码的html文档,例如:
var Test = React.createClass({
getInitialState: function() {
return {storage: this.props.storage};
},
render: function() {
return (
<h2>
{this.state.storage}
</h2>
);
}
});
在另一个类AppMan中,我有一个名为storageLeft
的属性。 如果我将Test组件渲染为:
<Test storage={AppMan.storageLeft}/>
每当在AppMan类中更改storageLeft
时,更新Test
组件的正确方法是什么? 我不确定将其作为组件的属性传递是否正确。 最初,我能想到的就是执行setInterval并不断执行this.setState({storage: AppMan.storageLeft});
或类似的规定。 还有更好的主意吗?
通过道具设置状态是反模式 。 您应该将storageLeft
保存为AppMan组件的状态,然后将该状态作为道具传递给Test组件。 更改状态后,组件会自动重新渲染其自身及其子级(如果需要)。
该文档指出:
为了实现交互,我们向组件引入了可变状态。 this.state对组件是私有的,可以通过调用this.setState()进行更改。 状态更新时,组件会重新渲染自己。
这样,当您传递状态作为道具时,您的组件将保持同步。
AppMan.js
<Test storage={this.state.storageLeft} />
Test.js
var Test = React.createClass({
render: function() {
return (
<h2>
{this.props.storage}
</h2>
);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.