class PlayerControls extends React.Component {
constructor(props) {
super(props)
this.state = {
loopActive: false,
shuffleActive: false,
}
}
render() {
var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"
return (
<div className="player-controls">
<FontAwesome
className="player-control-icon"
name='refresh'
onClick={this.onToggleLoop}
spin={this.state.loopActive}
/>
<FontAwesome
className={shuffleClassName}
name='random'
onClick={this.onToggleShuffle}
/>
</div>
);
}
onToggleLoop(event) {
// "this is undefined??" <--- here
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
我想在toggle上更新loopActive状态,但该对象在处理程序中未定义。根据教程文档,我这应该是指组件。我遗漏了什么吗?
我想解释一下为什么这是没有定义的:
如果在非箭头函数中使用this,则在非严格模式时,this将绑定到全局对象。但在严格模式下,这将是未定义的(https://www.w3schools.com/js/js_this.asp)。
而且ES6的模块总是处于严格模式(javascript:在模块中使用strict是不必要的)。
你可以在ontogglloop函数中绑定这个PlayerControls组件的实例,在构造函数中使用bind方法:
constructor(props) {
super(props)
this.state = {
loopActive: false,
shuffleActive: false,
}
this.onToggleLoop = this.onToggleLoop.bind(this)
}
或者使用箭头函数:
onToggleLoop = (event) => {
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
箭头函数没有上下文,因此箭头函数中的this将表示定义箭头函数的对象。
您应该注意到,这取决于函数的调用方式
即:当一个函数作为一个对象的方法被调用时,它的this被设置为该方法被调用的对象。
它可以在JSX上下文中作为组件对象访问,因此您可以像此方法一样内联调用所需的方法。
如果你只是把引用传递给函数/方法,react似乎会把它作为独立的函数调用。
onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined
onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object
我想解释一下为什么这是没有定义的:
如果在非箭头函数中使用this,则在非严格模式时,this将绑定到全局对象。但在严格模式下,这将是未定义的(https://www.w3schools.com/js/js_this.asp)。
而且ES6的模块总是处于严格模式(javascript:在模块中使用strict是不必要的)。
你可以在ontogglloop函数中绑定这个PlayerControls组件的实例,在构造函数中使用bind方法:
constructor(props) {
super(props)
this.state = {
loopActive: false,
shuffleActive: false,
}
this.onToggleLoop = this.onToggleLoop.bind(this)
}
或者使用箭头函数:
onToggleLoop = (event) => {
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
箭头函数没有上下文,因此箭头函数中的this将表示定义箭头函数的对象。