美文网首页
关于React组件,要给回调使用的函数绑定this的理解

关于React组件,要给回调使用的函数绑定this的理解

作者: xuehairong | 来源:发表于2020-06-12 14:41 被阅读0次

今天在看react官网,看到下面的代码

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    // 为了在回调中使用 `this`,这个绑定是必不可少的    
    this.handleClick = this.handleClick.bind(this);  
  }
  handleClick() {    
    this.setState(state => ({      isToggleOn: !state.isToggleOn    })); 
  }
  render() {
    return (
      <button onClick={this.handleClick}>        
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
   }
}
ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

官网有如下注释

你必须谨慎对待 JSX 回调函数中的 this,在 JavaScript 中,class 的方法默认不会绑定 this。如果你忘记绑定 this.handleClick 并把它传入了 onClick,当你调用这个函数的时候 this 的值为 undefined

我记得class好像不用单独去绑定this,于是我去看了es6,确实不用,但react官网的意思是 当函数作为回调函数被调用时,上面代码中onClick={this.handleClick}其实就是把handleClick传入onClick作为回调函数,可以理解为如下代码

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
  getAsyncData(cb) {
    return cb();
  }
  print(){
    return this.getAsyncData(this.toString)
  }
}
var o=new Point(1,2)
o.print()//此时报错 this is undefined

解决办法有很多,其中一种就可以用bind

 print(){
    return this.getAsyncData(this.toString.bind(this))
  }

相关文章

  • 关于React组件,要给回调使用的函数绑定this的理解

    今天在看react官网,看到下面的代码 官网有如下注释 你必须谨慎对待 JSX 回调函数中的 this,在 Jav...

  • 学习react总结知识点

    传统HTML中 handleclick函数自动绑定了this,而react中 需要手动绑定,下面是回调函数绑定...

  • 「React Native」Event Bus,消息总线

    (一)父子间组件通信:   一般使用props,回调函数进行通信。(二)跨组件之间通信:  (1)React Na...

  • React中的this绑定

    在编写react组件时经常需要进行函数的this绑定,使用ES6方式创建的组件中的函数必须手动绑定this,thi...

  • 代码规范

    React组件中如果添加了监听横竖屏切换的回调函数,则在该组件的willUnmount的时候需要卸载此监听回调。

  • 事件处理

    React元素绑定事件有两点需要注意: 使用箭头函数 使用组件方法

  • React 事件

    事件绑定的方法 ① 在constructor 中 手动绑定 ② 使用实验性属性 ③ 在回调中使用箭头函数 ④ 使用...

  • react native 单选框

    react native 单选框的实现RadioView.js组件 父组件调用使用 回调 效果:

  • React组件中绑定回调

    原文:Binding callbacks in React components 在组件中给事件绑定处理函数是很常...

  • React.withContext和getChildContex

    1、React.withContext会执行一个指定上下文信息的回调函数,任何在这个回调函数里面渲染的组件都有这个...

网友评论

      本文标题:关于React组件,要给回调使用的函数绑定this的理解

      本文链接:https://www.haomeiwen.com/subject/urwgtktx.html