在React的onClick事件中重置输入值

我知道这很简单,但是这对我来说有点困惑:(

为什么在以下情况下的输入值未重置。

handleReset() {
  this.setState({ data: "" });
}

<button onClick={this.handleReset}>Reset</button>

但是,当我在onClick事件中使用内联方式时,我可以重置输入值。

<button onClick={()=>{ this.setState({ data: "" });}}>Reset</button>

我使用CodePen创建了一个工作示例。谁能指导我做错了什么。

catheone 回答:在React的onClick事件中重置输入值

您需要将handleReset()函数绑定到该类,或使用箭头函数。 this的范围发生其他变化。

尝试使用箭头功能(绑定范围):

handleReset = () => {
  this.setState({ data: "" });
}

另外5个示例,位于: https://www.freecodecamp.org/news/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56/

更新:

自动将方法绑定到其类实例的小型库。 https://www.npmjs.com/package/auto-bind

,

推荐方法

constructor(props) {
  super(props);
  this.handleReset = this.handleReset.bind(this);
}

handleReset() {
  this.setState({ data: "" });
}

<button onClick={this.handleReset}>Reset</button>
本文链接:https://www.f2er.com/3155880.html

大家都在问