我试图将我的React类转换为ES6,但是在此过程中遇到了一些困难。我想将绑定(bind)绑定(bind)到构造函数中,而不是在渲染 View 中。

现在,如果我有一个带有setState的根模块,它需要一个参数,例如:

constructor() {
    super();

    this.state = {
        mood: ""
    };

    this.updateMood(value) = this.updateMood.bind(this,value);
}

updateMood(value) {
    this.setState({mood: value});
}

然后,我将此函数传递给组件:
<customElement updateMood={this.updateMood}></customElement>

然后在customElement模块中,我有这样的东西:
constructor() {
    super();
}

update(e) {
    this.props.updateMood(e.target.value);
}

并在渲染中:
<input onChange={this.update} />

这是正确的方法吗?由于我无法正常工作;-(

最佳答案

您不能使用这种this.updateMood(value) = this.updateMood.bind(this,value);构造,因为它是语法错误。

你可以这样解决你的问题

class CustomElement extends React.Component {
  constructor() {
    super();
    this.update = this.update.bind(this);
  }

  update(e) {
    this.props.updateMood(e.target.value);
  }

  render() {
    return <input onChange={this.update} />
  }
}

class Parent extends React.Component {
  constructor() {
    super();

    this.state = {
        mood: ""
    };

    this.updateMood = this.updateMood.bind(this);
  }

  updateMood(value) {
    this.setState({ mood: value });
  }

  render() {
    return <div>
      <CustomElement updateMood={this.updateMood}></CustomElement>
      <h1>{ this.state.mood }</h1>
    </div>
  }
}

Example

07-24 09:50
查看更多