ReactJS - 在更改单独的类属性时更新组件

ReactJS - updating components when separate class property is changed

本文关键字:属性 更新 组件 单独 ReactJS      更新时间:2023-09-26

在我的项目中,我有一个带有一些反应代码的html文档,例如:

var Test = React.createClass({
  getInitialState: function() {
    return {storage: this.props.storage};
  },
  render: function() {
    return (
      <h2>
        {this.state.storage}
      </h2>
    );
  }
});

在另一个类AppMan中,我有一个名为storageLeft的属性。如果我渲染测试组件,例如:

<Test storage={AppMan.storageLeft}/>

每当 AppMan 类中更改storageLeft时,更新Test组件的正确方法是什么?我不确定将其作为组件的属性传递是否是正确的方法。最初,我能想到的就是做一个setInterval,并不断地做this.setState({storage: AppMan.storageLeft});或类似的事情。有什么更好的主意吗?

通过 props 设置状态是一种反模式。您应该将storageLeft保存在 AppMan 组件的状态中,然后将该状态作为 prop 传递给测试组件。当您更改组件的状态时,它会自动重新呈现其自身及其子组件(如果需要)。

文档指出:

为了实现交互,我们将可变状态引入 元件。this.state 是组件专用的,可以更改 通过调用 this.setState()。当状态更新时,组件 重新呈现自身。

这样,当您将状态作为 prop 传递时,您的组件将保持同步。

阿普曼.js

<Test storage={this.state.storageLeft} />

测试.js

var Test = React.createClass({
  render: function() {
    return (
      <h2>
        {this.props.storage}
      </h2>
    );
  }
});