class App3 extends React.Component{ // 初始化state state={ count:0 } render(){ // js逻辑代码写入JSX中导致代码显得混乱 return ( <div><h1>计数器:{this.state.count}</h1> <button onClick={()=>{ this.setState({ count:this.state.count + 1 }) }}>+1</button> </div/> ) } } // 渲染组件 ReactDOM.render(<App3 />,document.querySelector('#root'))
1. Arrow function method
Take advantage of the fact that the arrow function itself is not bound to this
render() method this is the component instance, which can be obtained to setState()
class App4 extends React.Component{ state={ count:0 } // 事件处理程序 onIncrement(){ console.log('事件处理程序中的this',this) this.setState({ count:this.state.count+1 }) } render(){ return ( <div><h1>计数:{this.state.count}</h1> <button onClick={()=>this.onIncrement()}>+1</button> </div> ) } } // 渲染组件 ReactDOM.render(<App4 />,document.querySelector('#root'))
2.Function.prototype.bind()
Use the bind method in ES5 to bind this in the event handler to the component instance
class App5 extends React.Component{ constructor(){ super() this.state={ count:0 } this.onIncrement=this.onIncrement.bind(this) } // 事件处理程序 onIncrement(){ console.log('事件处理程序中的this',this) this.setState({ count:this.state.count+1 }) } render(){ return ( <div><h1>数值:{this.state.count}</h1> <button onClick={this.onIncrement}>+1</button> </div> ) } } // 渲染组件 ReactDOM.render(<App5 />,document.querySelector('#root'))
3. Instance method of .class
利用箭头函数形式的class实例方法解决this指向问题
class App6 extends React.Component{ constructor(){ super() this.state={ count:0 } this.onIncrement=this.onIncrement.bind(this) } // 事件处理程序 onIncrement=()=>{ console.log('事件处理程序中的this',this) this.setState({ count:this.state.count+1 }) } render(){ return ( <div><h1>数值:{this.state.count}</h1> <button onClick={this.onIncrement}>+1</button> </div> ) } } // 渲染组件 ReactDOM.render(<App6 />,document.querySelector('#root'))