react中绑定this

2019-11-04  本文已影响0人  any_5637

在开发过程中,react定义的组件中,如果不为事件处理程序绑定this:

  import React    from 'react';
  import ReactDOM from 'react-dom';

  export default class ThisTest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'hh',
    }
  }
  onClick() {
    console.log('点我');
    console.log(this.state.name);
    console.log(this);
  }
  render() {
    return (
    <div>
      <button onClick={this.onClick}>点我</button>
    </div>
    )
  }
  }
image.png

当我点击按钮,页面将报错,我将this打印出来,this的值为‘undefined’,onClick方法没有this的上下文,因此需要我们手动的给它绑定this。通过我的了解,总结了一下几个方式来绑定this:

render方法调用的时候使用.bind(this)进行绑定

  import React    from 'react';
  import ReactDOM from 'react-dom';

  export default class ThisTest extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        name: 'hh',
      }
    }
    onClick() {
      console.log(this.state.name);
      console.log(this);
    }
    render() {
      return (
        <div>
          <button onClick={this.onClick.bind(this)}>使用bind方式绑定this</button>
        </div>
      )
    }
  }

绑定this之后,这里this指向整个组件对象实例。


image.png

render方法调用的时候使用箭头函数进行绑定

使用箭头函数自动绑定了定义此函数作用域的this,而不需要我们手动的使用bin绑定。

  <div>
    <button onClick={() =>this.onClick()}>使用箭头函数绑定this</button>
  </div>

构造器内声明

通过在构造器中给时间处理程序绑定this,可以获得整个dom实例。这种绑定方式的好处在于仅需要进行一次绑定,而不需要每次调用事件监听器时去执行绑定操作。

  import React    from 'react';
  import ReactDOM from 'react-dom';

  export default class ThisTest extends React.Component {
    constructor(props) {
      super(props);
      this.onClick = this.onClick.bind(this);
      this.state = {
        name: 'hh',
      }
    }
    onClick() {
      console.log(this.state.name); 
      console.log(this);
    }
    render() {
      return (
        <div>
          <button onClick={() =>this.onClick()}>在构造器内绑定this</button>
        </div>
      )
    }
  }

使用lodash-decorators的Bind()方法绑定

首先需要将项目支持装饰器:
在根目录下面新建.babelr文件,写入:

  {
    "presets": ["@babel/preset-env"],
    "plugins": [
      ["@babel/plugin-proposal-decorators", { "legacy": true }],
      ["@babel/plugin-proposal-class-properties", { "loose": true }]
    ]
  }

然后就是导入的方法使用

  // 导入lodash-decorators下的Bind方法
  import { Bind } from 'lodash-decorators';

  // 在函数的头上使用bind方法,就会将this指向组件实例
  @Bind()
  onClick(event){
    console.log(this);
  }
  
  <button onClick={this.onClick}>点我</button>
上一篇 下一篇

猜你喜欢

热点阅读