简体   繁体   中英

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'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).

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. You could do:

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

You can also use the componentDidUpdate lifecycle:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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