Meteor 为什么在React onClick()方法中,`this`关键字引用的是窗口而不是组件
我以为Meteor 为什么在React onClick()方法中,`this`关键字引用的是窗口而不是组件,meteor,reactjs,Meteor,Reactjs,我以为this关键字总是指React中的组件,但在我下面中的toggleStyle方法中,this返回的是窗口对象,而不是React组件对象。有人能帮我理解这是为什么吗 renderDeviceToggle() { var arrowAnimation = { rotateX: this.state.expanded ? 180 : 0, transformOriginY: [ '42%', '42%' ] }; let toggleS
this
关键字总是指React中的组件,但在我下面中的toggleStyle
方法中,this
返回的是窗口对象,而不是React组件对象。有人能帮我理解这是为什么吗
renderDeviceToggle() {
var arrowAnimation = {
rotateX: this.state.expanded ? 180 : 0,
transformOriginY: [ '42%', '42%' ]
};
let toggleState = function () {
// 'this' is the window
console.log("in toggleState: this: ", this)
this.setState({expanded: !this.state.expanded});
};
return (
<div className="device-toggle" onClick={toggleState}>
<div>{console.log("in return: this is the component: ", this)}</div>
<div className="device-icon icon huge"></div>
<VelocityComponent duration={300} animation={arrowAnimation}>
<div className="icon color-blue flex">
<i className="icon-caret-down"></i>Hi
</div>
</VelocityComponent>
</div>
);
},
render() {
return (
<div>
<div className="panel panel-default">
<div className="panel-heading">
<div className="pull-right text-right">
<p><a href="/addOrder" className="pull-right">New order </a></p>
<p><a href="#"> View all</a></p>
</div>
<h4>Top orders</h4>
</div>
<div className="panel-body">
{ this.data.orders ?
this.renderOrderTable() :
<p>Loading</p> }
</div>
<div>
{this.renderDeviceToggle()}
</div>
</div>
</div>
);
}
renderDeviceToggle(){
变量箭头动画={
rotateX:this.state.expanded?180:0,
变革性:['42%,'42%']
};
让toggleState=函数(){
//“这”是窗户
log(“切换状态:this:,this”)
this.setState({expanded:!this.state.expanded});
};
返回(
{console.log(“返回:这是组件:”,this)}
你好
);
},
render(){
返回(
顶级订单
{this.data.orders?
此.renderRoderTable():
加载}
{this.renderDeviceToggle()}
);
}
您可以使用箭头函数获得词汇绑定此
:
let toggleState = () => {
// 'this' should be the component
console.log("in toggleState: this: ", this)
this.setState({expanded: !this.state.expanded});
};
或者显式地绑定上下文:
let toggleState = function () {
// 'this' should be the component
console.log("in toggleState: this: ", this)
this.setState({expanded: !this.state.expanded});
}.bind(this);
关于这个如何以及为什么在JS中工作,这里有一个很好的解释发生这种情况的原因是因为React只将类中的顶级函数绑定到“this”。因此,在这种情况下,
render
和renderDeviceToggle
都像您预期的那样绑定。但是,在renderDeviceToggle
中,您创建了一个新函数,toggleState
,React不知道该函数。因此,创建函数时,此代码在正常javascript规则下工作
正如在另一个答案中提到的,要解决这个问题,您需要使用箭头上下文或显式地将新函数绑定到“this”