- 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值
网友评论