如何在作为 "prop" 传递给子组件的函数中使用 "this"?
How to use "this" in a function passed as a "prop" to a subcomponent?
我正在使用 ReactJS。
我有一个呈现子组件的组件,我将函数作为 prop
传递。但是,我不能在函数处理程序中使用 this
。
var MyComponent = React.createClass({
onChildStatusChanged: function () {
// this.state is undefined, of course, because this function hasn't been called from this object context.
},
render: function() {
return <div>
<SubComponent onStatusChanged={this.onChildStatusChanged} />
</div>
}
如何在 onChildStatusChanged
中使用 this
?
您可以使用 bind
.
将当前 this
上下文绑定到 this.onChildStatusChanged
函数
this.onChildStatusChanged.bind(this)
bind
函数将 return 等于 onChildStatusChanged
的函数,但 this
上下文设置为您指定的上下文。
bind
是一个 ES5 特性,所以如果你的目标系统是 < ES5,你将需要 polyfil 这个函数。
更新
您在当前事件分配中添加绑定:
<SubComponent onStatusChanged={this.onChildStatusChanged.bind(this)} />
我正在使用 ReactJS。
我有一个呈现子组件的组件,我将函数作为 prop
传递。但是,我不能在函数处理程序中使用 this
。
var MyComponent = React.createClass({
onChildStatusChanged: function () {
// this.state is undefined, of course, because this function hasn't been called from this object context.
},
render: function() {
return <div>
<SubComponent onStatusChanged={this.onChildStatusChanged} />
</div>
}
如何在 onChildStatusChanged
中使用 this
?
您可以使用 bind
.
this
上下文绑定到 this.onChildStatusChanged
函数
this.onChildStatusChanged.bind(this)
bind
函数将 return 等于 onChildStatusChanged
的函数,但 this
上下文设置为您指定的上下文。
bind
是一个 ES5 特性,所以如果你的目标系统是 < ES5,你将需要 polyfil 这个函数。
更新
您在当前事件分配中添加绑定:
<SubComponent onStatusChanged={this.onChildStatusChanged.bind(this)} />