Incrementing state value by one using React

后端 未结 8 1827
不知归路
不知归路 2021-01-30 17:33

In React I am trying to make a button increment a value stored in state. However using the code below function my value is set undefined or NaN when using handleClick.

相关标签:
8条回答
  • 2021-01-30 18:34

    Hello there, try these codes to increment your value

    class Counter extends React.Component{
     constructor(props){
       super(props);
         this.addOne = this.addOne.bind(this);
           this.state = {
             count : 0 
           }
        }
    
    addOne() {                              // addOne as HandleClick
      this.setState((preState) => {
        return {
          count : preState.count + 1
          };
       });
     }
    
    render() {
       return (
          <div>
            <h1>Count : {this.state.count}</h1>
            <button onClick={this.addOne}>+1</button>
          </div>
         );
       }
     }
    
    ReactDOM.render(<Counter />, document.getElementById('YOUR-ID'));
    
    0 讨论(0)
  • 2021-01-30 18:34

    This is the shortest code for that. First, initialize the state, then perform a method to increment.

    state = {
        counter: 0
      }
    
    increaseHandler = () => {
        let counter = this.state.counter
        counter += 1
        this.setState({counter: counter})
      }
    
    0 讨论(0)
提交回复
热议问题