只要在构造函数中绑定类方法,最终的整体输出都是一样的。
以下,一旦编译,以相同的方式运行。
class Foo extends React.Component {
constructor(props) {
super(props)
this.handleBla = this.handleBla.bind(this)
}
handleBla() {
}
}
class Foo extends React.Component {
handleBla = () => {
}
}
你说“为什么this
在 React 中绑定时this
不会改变”。这实际上不是真的 - 所有事件处理程序都会更改this
. 因此,请确保使用箭头函数或绑定事件处理程序。
转译
一旦你通过 babel 转译了两者,你会发现几乎没有区别。箭头函数被简单地映射到 _this (还记得 ES6 之前的这个技术吗?)
var Foo = function () {
function Foo() {
_classCallCheck(this, Foo);
this.handleBla = this.handleBla.bind(this);
}
_createClass(Foo, [{
key: "handleBla",
value: function handleBla() {
console.log(this);
}
}]);
return Foo;
}();
var Foo = function Foo() {
var _this = this;
_classCallCheck(this, Foo2);
this.handleBla = function () {
console.log(_this);
};
};
概括:
它基本上是一样的,但是如果您打算将它们与事件一起使用并引用组件,则必须使用绑定上下文(通过箭头函数或绑定)。这非常常见,因为大多数事件处理程序都引用state
, setState
or props
,因此您将需要正确的this