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()
}
我想更新切换时的loopActive
状态,但this
对象在处理程序中未定义。根据教程文档,我 this
应该引用该组件。我错过了什么吗?
最佳答案
ES6 React.Component
不会自动将方法绑定(bind)到自身。您需要自己在构造函数
中绑定(bind)它们。像这样:
constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}
关于javascript - react : "this" is undefined inside a component function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33973648/