Incrementing state value by one using React

后端 未结 8 1829
不知归路
不知归路 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 (
          

    Count : {this.state.count}

    ); } } ReactDOM.render(, document.getElementById('YOUR-ID'));

提交回复
热议问题