解决指向
箭头函数
onLog1 = () => { // 箭头函数解决this指向的问题 console.log(this); } 箭头函数:<input type="button" onClick={this.onLog1} value="提交1" />
调用时使用箭头函数
onLog2(text) { console.log(text); console.log(this); } 调用时,使用箭头函数:<input type="button" onClick={() => { this.onLog2('text') }} value="提交2" />
调用时,使用bind函数
onLog3(text) { console.log(this); console.log(text); } 调用时,使用bind函数:<input type="button" onClick={this.onLog3.bind(this, 'text')} value="提交3" />
通过bind改变this指向
constructor(props) { super(props); this.state = { } // 通过bind改变this指向 this.onLog = this.onLog.bind(this) } onLog() { console.log(this); } 通过bind: <input type="button" onClick={this.onLog} value="提交" />