且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用反应检测变化

更新时间:2023-02-26 15:07:01

试着想象这里有两件事:

  • 组件(COMPONENT)本身,以及
  • 组件之外的东西(OUTSIDE):

组件内部的变化

您需要调用this.setState(),这将更新当前组件内部的状态,并随后触发此组件的更新(自动调用render())

外部变化

这会触发这个 COMPONENT 的 props/newProps 被更新,随后你的组件通过在组件内部调用 this.setState() 来更新(componentWillReceiveProps 是 React 的生命周期方法)

class MyComponent 扩展 React.Component {//最初如何将状态设置为 MyComponent构造函数(道具){超级(道具);this.state = {name: this.props.name};}//要在 MyComponent 内部调用的自己的方法更新名称(e){const newName = e.target.value;if (this.state.name !== newName) {this.setState({name:newName});}}//外部变化componentWillReceiveProps(nextProps) {const newName = nextProps.name;if (this.state.name !== newName) {this.setState({name:newName});}}使成为() {返回(<div>{this.state.name}<输入类型="文本"onChange={this.updateName.bind(this)}值={this.state.name}/>