【 React

/**
     *  报错:
     *  Cannot read property 'setState' of undefined
     *  原因: this指向不一致。btnAddCount中的this 和render中的this
     *  解决方法:
     *      方式一: 使用箭头函数 () => { }  箭头函数可以改变this指向,即谁调用,this指向谁
     *      方式二: 绑定函数时,添加 ‘ .bind(this)’  onClick={this.btnSubCount.bind(this)
     *
 *      在 React 里面,要将类的原型方法通过 props 传给子组件,传统写法需要 bind(this),否则方法执行时 this 会找不到:

     <button onClick={this.handleClick.bind(this)}></button>
     或者

     <button onClick={() => this.handleClick()}></button>
     * */
    /*btnAddCount(){
        this.setState({
            // 不要直接修改state的值  this.state.count++
            count: this.state.count + 1
        })
    }*/
    btnAddCount =  () => {
        this.setState({
            // 不要直接修改state的值 this.state.count++
            count: this.state.count + 1
        });
    };
    btnSubCount(){
        this.setState({
            count: this.state.count - 1
        })
    }
    render() {
        return (
            <div>有状态组件:
                <h2>计数器: {this.state.count}</h2>
                <button onClick={this.btnAddCount}>+1</button>
                <button onClick={() => this.btnAddCount()}>+1</button>
                <button onClick={this.btnSubCount.bind(this)}>-1</button>
                <button onClick={() => {
                    this.setState({
                        count: this.state.count - 1
                    })
                }}>-1</button>
            </div>
        )
    }
}
// 渲染这个组件
ReactDOM.render(<StateUseDemo />, document.getElementById('root'));

ES5 方法

 // ES5方法绑定this 在constructor中添加
    this.btnAddCount =  this.btnAddCount.bind(this);
原文地址:https://www.cnblogs.com/YangxCNWeb/p/11965620.html