react 类组件事件绑定 this 指向问题

react 类组件事件绑定 this 指向问题

1.    普通绑定 - 触发单击事件

class App extends React.Component{
    // 事件函数
    fn1(){
        console.log('fn1')
        console.log(this) // undefined
    }
    render(){
        <button onClick={ this.fn1 }>按钮1</button>
    }
}
  • 单击 按钮1 ,控制台打印结果如下:

      


this 指向 undefined ?

  • 利用 JS 类实验得到以下结果:

    // 定义 Star 类
    class Star {
        thisDirection() {
            console.log(this);
        }
    }
    
    var star = new Star();
    star.thisDirection(); // 实例调用
    const x = star.thisDirection; // 保存方法
    x(); // 直接调用
    • 控制台打印结果如下:

              

  • 类中所有的方法,在局部默认开启了严格模式,它不敢指向 window 所以指向了 undefined


结论:在 React 事件普通绑定中,由于直接调用了类中的方法,所以 this 指向 undefined

为了解决 this 指向问题,React 还提供了其他绑定方式:

2. bind 绑定:

  • 通过bind改变点击事件内的this指向外部组件内this (使用较多)

    class App extends React.Component{
       // 事件函数
       fn2(){
           console.log('fn2');
           console.log(this); // Class
       }
       render(){
           <button onClick={ this.fn2.bind(this) }>按钮2</button>
       }
    }
  • 通过在构造函数constructor内使用bind对函数内的this重定向

    class App extends React.Component{
       constructor(){
           super() // ES6 类继承类, constructor() 里面用 this 必须调用 super() 函数
           // this 指向当前类组件
           // 调用公用的 属性 和 方法 必须加 this
           this.fn3 = this.fn3.bind(this)
       }
       // 事件函数
       fn3(){
           console.log('fn3');
           console.log(this); // Class
       }
       render(){
           <button onClick={ this.fn3 }>按钮3</button>
       }
    }

3.    箭头函数绑定:

  • 通过使用箭头函数来指向外部组件内this (使用较多)

    class App extends React.Component{
        // 事件函数
        fn4(){
            console.log('fn4');
            console.log(this); // Class
        }
        render(){
            <button onClick={ () => this.fn4() }>按钮4</button>
        }
    }
  • 将事件函数写成箭头函数来指向外部组件内this (使用较多)

    class App extends React.Component{
        fn5 = () => {
            console.log('fn5');
            console.log(this); 
        }
        render(){
            <button onClick={ this.fn5 }>按钮5</button>
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值