React .bind()

作者: rangel | 来源:发表于2017-08-15 10:27 被阅读0次
  1. 当使用es5时,是不需要用.bind()的。
    当使用es5 时,React会自动帮助我们给每一个function绑定一个this,所以我们不再需要手动绑定。
    例如:
var HelloWorld = React.createClass({
  getInitialState() {
    return { message: 'Hi' };
  },

  logMessage() {
    // this magically works because React.createClass autobinds.
    console.log(this.state.message);
  },

  render() {
    return (
      <input type="button" value="Log" onClick={this.logMessage} />
    );
  }
});
  1. 当使用es6时,es6不会再自动的帮助我们绑定函数,这时我们就需要使用.bind(this).
    例如:
class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: 'Hi' };
  }

  logMessage() {
    // This works because of the bind in render below.
    console.log(this.state.message);
  }

  render() {
    return (
      <input type="button" value="Log" onClick={this.logMessage.bind(this)} />
    );
  }
}
  1. 在es6中,我们也可以使用箭头函数来避免使用.bind(this)
    例如:
class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: 'Hi' };
  }

  logMessage() {
    // This works because of the arrow function in render below.
    console.log(this.state.message);
  }

  render() {
    return (
      <input type="button" value="Log" onClick={() => this.logMessage()} />
    );
  }
}

同样,我们也可以在logMessage的实现中国使用箭头函数。
例如:

class HelloWorld extends React.Component {
  // Note that state is a property,
  // so no constructor is needed in this case.
  state = {
    message: 'Hi'
  };

  logMessage = () => {
    // This works because arrow funcs adopt the this binding of the enclosing scope.
    console.log(this.state.message);
  };

  render() {
    return (
      <input type="button" value="Log" onClick={this.logMessage} />
    );
  }
}

原文链接:https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56

相关文章

  • React .bind()

    当使用es5时,是不需要用.bind()的。当使用es5 时,React会自动帮助我们给每一个function绑定...

  • react bind

    前置知识 原因:在temp作为中间量转换的时候丢失了this的指向 在react中 bind的原理同上方一致,在j...

  • react性能优化 不要再component的props中使用箭头函数或者bind,因为每次使用箭头函数和bind...

  • React bind this的五种方式介绍

    react中避免不了经常需要对this进行操作,而事件默认react是不被bind到当前react实例上的,需要手...

  • react系列-bind this

    原文链接:https://segmentfault.com/a/1190000007207233对于大多数前端开发...

  • react的bind

    问题描述 今天重构项目的路由代码,遇到了一个问题,在app.js 的文件中,我使用react-router路由如下...

  • React系列bind this

    在实际开发中遇到事件不执行的情况,一直不理解bind函数,正好理理,代码如下 this.handleClick中t...

  • react的bind(this)

    在调用this.setState()的时候出现了this为undefined的情况,如何处理。(四种写法,其中一种...

  • 面试官问:能否模拟实现JS的bind方法

    前言 用过React的同学都知道,经常会使用bind来绑定this。 那么面试官可能会问是否想过bind到底做了什...

  • react组件中事件处理的几种写法,几种写法的区别,bind(t

    react组件中事件处理的几种写法,几种写法的区别,bind(this)传自定义的参数 一、在React元素绑定事...

网友评论

    本文标题:React .bind()

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