美文网首页
关于react中es5和es6写法中的this

关于react中es5和es6写法中的this

作者: lueyoo | 来源:发表于2018-05-02 10:10 被阅读0次
  • es5的代码:
  var React = require('react');
    var MyComponent = React.createClass({
        handleClick: function() {
            React.findDOMNode(this.refs.myTextInput).focus();
        },
        render: function() {
            return (
                <div>
                    <input type="text" ref="myTextInput" />
                    <input type="button" value="Focus the text input" onClick= {this.handleClick} />
                </div>
            );
        }
    });
    
    module.exports = React.createClass({
        render: function() {
            return (
                <div>
                    <MyComponent />
                </div>
            );
        }

});

  • es6的代码:
import React,{Component} from 'react';
class FocusText extends Component{
  handleClick(){
    React.findDOMNode(this.refs.myText).focus();
  }
  render(){
    return(
      <div>
        <input type="text" ref="myText" />
        <input type="button" value="focus the text input" onClick={this.handleClick.bind(this)} />
      </div>
    );
  }
}
class RepeatArray extends Component{
  constructor() {
    super();
  }
  render(){
    return (
      <div>
      <FocusText />
      </div>
    );
  }
}
export default RepeatArray;
  • 问题:为什么es5写法中的onclick事件的处理函数不需要绑定this,但是es6写法中的onclick事件处理函数需要绑定this?es6写法中绑定前的this指向是什么?
    其实经常看到react中使用的es6需要绑定this,有时候在constructor中绑定再用,其实为什么需要这样的?在constructor中绑定和像上面es6例子中那样绑定有什么差别?为什么es5写法中却不需要绑定呢?

  • 答案:因为用ES5的createClass的写法,React会对里面的方法进行this绑定。而用ES6的extends Component并不会进行this绑定。

  • 解决方法:
    按照你说的,每个方法都进行this.handleClick.bind(this)方法定义的时候,用箭头函数定义,ES6会给这个方法自动绑定this
    这么调用也可以: onClick={(e)=>{ this.handleClick(e) }}
    上面三种方法都可以在handleClick中获取正确的this值

相关文章

网友评论

      本文标题:关于react中es5和es6写法中的this

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