
React框架的应用越来越广泛,所以作为前端工作人员来说,掌握的技术知识点需要不断增加,这些需要我们日常积累。今天分享下React一个开发TIPS:分享几种事件绑定this指向的方法。
箭头函数
利用箭头函数自身不绑定this的特点,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>
        )
    }
}Function.proptype.bind()
利用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>
        )
    }
}class的实例方法
利用箭头函数形式的class实例方法,该语法是实验性语法,但是由于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>
        )
    }
}    




网友评论文明上网理性发言 已有0人参与
发表评论: