美文网首页
React 的事件处理 之 this 的绑定方式

React 的事件处理 之 this 的绑定方式

作者: ___Jing___ | 来源:发表于2019-06-18 10:39 被阅读0次

在 Javascript 中,我们需要根据情况处理 this 的指向,那么,在 React 中,我们都是如何处理 this 的呢?下面让我们一起来看一下。

方法一: 在 constructor 中对函数进行 this 绑定,但是定义的方法多了,也比较麻烦。

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    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')
);

方法二: 通过箭头函数对 this 进行绑定,不过这个方法是“实验性”的,随时可能会变动,不太推荐。

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

方法三: 在函数调用时使用箭头函数进行绑定,这个是我在日常工作中常用的方法,比较推荐。

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

相关文章

  • React事件绑定this的几种方法

    React事件处理函数绑定this的集中方法 Follow me on GitHub React事件处理函数绑定t...

  • React 的事件处理 之 this 的绑定方式

    在 Javascript 中,我们需要根据情况处理 this 的指向,那么,在 React 中,我们都是如何处理 ...

  • 2018-11-07 react 事件处理

    react事件处理和dom事件处理是相似的。 react: Dom: 所以: React事件绑定属性的命名采用驼峰...

  • react随笔5 事件处理

    事件处理 React元素的事件处理和DOM元素的事件处理很相似,但是有一点语法上的不同: React事件绑定属性的...

  • React之事件处理

    React 元素的事件处理和DOM元素的很相似,但是有一点语法上的不同: 事件处理 React 事件绑定属性的命名...

  • React事件处理

    事件处理 React 元素的事件处理和 DOM元素的很相似。但是有一点语法上的不同:1、React事件绑定属性的命...

  • React笔记6(事件处理)

    事件处理 注意: React事件绑定的属性命名用驼峰方式,不用小写如果使用 jsx 的语法,就需要传入一个函数作为...

  • React学习之漫谈React

    事件系统 合成事件的绑定方式 Test 合成事件的实现机制:事件委派和自动绑定。 React合成事件系统的委托机制...

  • React的合成事件

    React的合成事件:React中声明的事件最终只绑定在document节点上, 通过事件代理的方式来实现事件的操...

  • React基础

    React处理事件与DOM相似: React事件绑定采用驼峰形式,而不是小写 JSX语法传入的函数是{}里面放置函...

网友评论

      本文标题:React 的事件处理 之 this 的绑定方式

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