N
N
Ninja Mate2016-05-15 13:18:37
JavaScript
Ninja Mate, 2016-05-15 13:18:37

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

1 answer(s)
Евгений Подивилов, 2016-05-16
@victorzadorozhnyy

Например можно написать функцию так:

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 question

Ask a Question

731 491 924 answers to any question