1.箭头函数
1.利用箭头函数自身不绑定this的特点;
2.render()方法中的this为组件实例,可以获取到setState();
class App 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> // 箭头函数中的this指向外部环境,此处为:render()方法 <button onClick={()=>this.onIncrement()}>+1</button> {/* <button onClick={this.onIncrement()}>+1</button> */} </div> ) } }
2.Function.proptype.bind()
1.利用ES5中的bind方法,将事件处理程序中的this与组件实例绑定到一起
class App extends React.Component{ constructor() { super() // 数据 this.state ={ count: 0 } // 第一中方法.bind 改变this指向,返回一个函数,不执行该函数 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> {/* <button onClick={this.onIncrement()}>+1</button> */} </div> ) } }
3.class的实例方法
1.利用箭头函数形式的class实例方法
2.该语法是实验性语法,但是由于babel的存在就可以直接使用
class App extends React.Component{ constructor() { super() // 数据 this.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> {/* <button onClick={this.onIncrement()}>+1</button> */} </div> ) } }
到此这篇关于React中事件绑定this指向三种方法的实现的文章就介绍到这了,更多相关React 事件绑定this指向内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)