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

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写法中却不需要绑定呢?

阅读 3.5k
1 个回答

因为用ES5的createClass的写法,React会对里面的方法进行this绑定。

而用ES6的extends Component并不会进行this绑定

解决方法:

  1. 按照你说的,每个方法都进行this.handleClick.bind(this)

  2. 方法定义的时候,用箭头函数定义,ES6会给这个方法自动绑定this

  3. 这么调用也可以: onClick={(e)=>{ this.handleClick(e) }}

上面三种方法都可以在handleClick中获取正确的this

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题