Answer the question
In order to leave comments, you need to log in
How to pass a State as an argument to a function in ReactJS?
How to correctly pass a state to a function in React, and then do this.setState?
//Хочу сделать универсально для разных стейтов и для _count задавать какой именно стейт.
counter(cond, _count){
if(cond==true) this.setState({ _count: _count+1})
}
<h1>{this.state.count}</h1>
<Button onClick={()=> this.counter(true, this.state.count) }> +++ </Button>
Answer the question
In order to leave comments, you need to log in
Например можно написать функцию так:
counter(cond, stateField){
if(cond==true) {
const newState = {};
newState[stateField] = this.state[stateField] + 1;
this.setState(newState);
}
}
<Button onClick={ this.counter.bind(this, true, someStateField }> +++ </Button>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question