简体   繁体   English

如何在一次单击(ReactJS)中调用 class 和 setState

[英]How to call a class and setState in one onClick(ReactJS)

I'm pretty new to React and I was wondering how I could call a function inside a class (so like this.handleChange) and an arrow function with a setState inside within one onClick of a button. I'm pretty new to React and I was wondering how I could call a function inside a class (so like this.handleChange) and an arrow function with a setState inside within one onClick of a button.

I've tried using commas and && in between the 2 lines of code.我尝试在两行代码之间使用逗号和 &&。

<button name="Plus" onClick={() => this.setState({ Operator: 'plus' }) && this.handlePlus}>+</button>

The above code is inside the render and return.上面的代码在渲染和返回中。

The expected result is that the code calls the function and changes the state.Instead it just changes the state(so only does the first part).预期的结果是代码调用了 function 并更改了 state。相反,它只是更改了状态(所以只有第一部分)。

Please help, thanks in advance!请帮忙,提前谢谢!

setState() has an optional second parameter that is a function that will be invoked once the state has been set. setState()有一个可选的第二个参数,即 function,一旦设置了 state,就会调用该参数。 You could do:你可以这样做:

this.setState({ Operator: 'plus' }, this.handlePlus);

You can also use the componentDidUpdate lifecycle:您还可以使用componentDidUpdate生命周期:

componentDidUpdate(prevProps, prevState) {
  if(this.state.Operator === 'plus' && prevState.Operator !== 'plus') {
    this.handlePlus();
  }
}
< button name = "Plus" onClick = { () => this.setState({ Operator: 'plus' }, () => this.handlePlus()) } > + < /button> this would work fine.or if you are looking for something like this.... you can handle multiple buttonClick event like this < button name = "Plus" value = "yourValue" onClick = { this.handleChange } > + < /button> handleChange = (e) => { const { name, value } = e.target; switch (name) { case 'Plus': this.setState({ [name]: value }); break; default: //enter code here break; } }

Just add the this.setState({ Operator: 'plus' } within the handlePlus function.只需在handlePlus this.setState({ Operator: 'plus' }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM