如果 React 没有在组件中自动为你绑定实例方法,会发生什么?



学习 React 并看到下面的代码,我读到 React 会自动为您绑定,因此 1 和 2 中的this运行良好。我想知道如果 React 没有自动为您绑定它,每个this中指的是什么?2this不会引用input元素,因此无法到达 1this吗?

var ContactForm = React.createClass({
propTypes: {
// ...
},
onNameInput: function(e) {
//1
this.props.onChange(Object.assign({}, this.props.value, {name: e.target.value}))
},
render: function() {
return React.createElement('form', {className: 'ContactForm'},
React.createElement('input', {
// ...
//2
onInput: this.onNameInput,
})
// ...
)
}
});

您可以通过查看此组件在扩展React.Component而不是使用createClass({})时将执行的操作来亲自尝试一下。

也就是说,这实际上只是一个JS问题。this根据其使用方式指向不同的东西。如果在上面的例子中没有发生自动绑定,那么如果你在浏览器中运行 React,它很可能指的是window。有关更多详细信息,请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this。

2 这不是指输入元素,因此无法到达 1 这个吗?

this#2 在其周围函数的范围内,特别是render函数。它指向该函数的this范围,在本例中为组件实例。在分配onInput: this.onNameInput期间,您将从组件实例中取消引用onNameInput,因此当您进行该分配时,它可能不再绑定到该实例。如果onNameInput从未被绑定,那么当它被称为它时,它的this将是window

最新更新