react事件处理函数绑定

2020-09-03  本文已影响0人  魔仙堡杠把子灬

遇事缓一缓,说话停一停 我是李大玄

前端QQ群: 981668406
在此附上我的QQ: 2489757828 有问题的话可以一同探讨
我的github: 李大玄
我的私人博客: 李大玄
我的简书: 李大玄
我的CSDN: 李大玄
我的掘金: 李大玄
这样定义的函数 打印出来的this 是undefined, 因为函数的作用域不一样,所有这样写是不行的

updateUser () {
    console.log(this); // undefined
    this.setState({
      name: '李继玄',
      age: '19'
    })
  }
  render() {
    return <div>
        <button onClick={this.updateUserBind}>数据更新bind</button>
        <hr></hr>
      </div>
  }

介绍三中绑定函数的方法

第一种 使用箭头函数的方式

updateUser = () => {
    console.log(this); // undefined
    this.setState({
      name: '李继玄',
      age: '19'
    })
  }
  render() {
    return <div>
        <button onClick={this.updateUserBind}>数据更新bind</button>
        <hr></hr>
      </div>
  }

第二种 在初始化的时候绑定this,改变作用域

class Hello extends React.Component {
  constructor(props) {
    super(props);
    /* 初始化阶段 */
    this.state = {
      name: '李大玄',
      age: 18
    };
    this.updateUserBind = this.updateUserBind.bind(this); // 这里绑定
  }
  updateUserBind() {
    console.log(this);
   
  }
  render() {
    /* 组件加载或者数据更新  会执行 reader 方法  */
    console.log('组件加载或者数据更新  会执行 reader 方法');
    return <div>
        <button onClick={this.updateUserBind}>数据更新bind</button>
        <hr></hr>
      </div>
  }
};

第三种 依旧是箭头函数

class Hello extends React.Component {
  constructor(props) {
    super(props);
    /* 初始化阶段 */
    this.state = {
      name: '李大玄',
      age: 18
    };
  }
  updateUserBind() {
    console.log(this);
   
  }
  render() {
    /* 组件加载或者数据更新  会执行 reader 方法  */
    console.log('组件加载或者数据更新  会执行 reader 方法');
    return <div>
        <button onClick={ () => this.updateUserBind}>数据更新bind</button>
        <hr></hr>
      </div>
  }
};

第四种 依旧是bind

class Hello extends React.Component {
  constructor(props) {
    super(props);
    /* 初始化阶段 */
    this.state = {
      name: '李大玄',
      age: 18
    };
  }
  updateUserBind() {
    console.log(this);
   
  }
  render() {
    /* 组件加载或者数据更新  会执行 reader 方法  */
    console.log('组件加载或者数据更新  会执行 reader 方法');
    return <div>
        <button onClick={ this.updateUserBind.bind(this)}>数据更新bind</button>
        <hr></hr>
      </div>
  }
};
上一篇 下一篇

猜你喜欢

热点阅读