Incrementing state value by one using React

后端 未结 8 1843
不知归路
不知归路 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:31

    class SkuVariantList extends React.Component {
        constructor(props) {
          super(props)
          this.state = {
            clicks: 0
          };
          this.clickHandler = this.clickHandler.bind(this)
        }
    
        componentDidMount() {
          this.refs.myComponentDiv.addEventListener('click', this.clickHandler);
        }
    
        componentWillUnmount() {
          //this.refs.myComponentDiv.removeEventListener('click', this.clickHandler);
        }
    
        clickHandler() {
          var clk = this.state.clicks
          this.setState({
            clicks: clk + 1
          });
        }
    
        render() {
          let children = this.props.children;
    
          return (
            

    My Component ({this.state.clicks} clicks})

    {this.props.headerText}

    {children}
    ); } }

提交回复
热议问题