React 函数的 this 绑定

        constructor() {
          super();
          console.log("constructor");
          console.log(this); // App {props: undefined, context: undefined, refs: {…}, updater: {…}}
        }

        render() {
          console.log("render");
          console.log(this); // App {props: {…}, context: {…}, refs: {…}, updater: {…}, _reactInternals: FiberNode, …}
          return <button onClick={this.show}>显示</button>;
        }

        show() {
          console.log("show");
          console.log(this); // undefined
        }
      }

      root.render(<App />);

1. 类中的 constructor 函数的 this 指向实例对象

2. render 函数是实例创建好之后,通过实例对象调用的,所以this是指向实例对象的。

3. show 方法不是实例对象调用的,所以是 undefined 

为什么 this 会丢失?

      class App {
        show() {
          console.log("show");
          console.log(this);
        }
      }

      const app = new App();
      let temp = app.show;
      app.show(); // App {}: Object
      temp();     // undefined

为什么调用 temp 没有指向 window 却是 undefined ? 

类中的方法都开启了严格模式。

 return <button onClick={this.show}>显示</button>;

show 是 onClick 函数的回调,不是实例对象调用的,是直接调用的,类中有严格模式,所以 show 中的 this 是 undefined。

解决方式:

1. bind 

      class App {
        constructor() {
          this.show = this.show.bind(this);
        }
        show() {
          console.log("show");
          console.log(this);
        }
      }

2. 箭头函数(show函数中没有 this,用了类中的 this)

      const root = ReactDOM.createRoot(document.querySelector("#root"));

      class App {
        show = () => {
          console.log(this);
        };
      }

      const app = new App();
      app.show();
      let temp = app.show;
      temp();

3.  直接传入一个箭头函数

        btnClick() {
          console.log("btnClick", this);
          this.setState({ counter: 9999 });
        }

        render() {
          return <button onClick={() => this.btnClick()}>按钮3</button>;
        }

onClick 函数回调时,执行箭头函数,箭头函数再执行 btnClick 函数。this.btnClick()这里的 this 是组件实例对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值