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应该参考该组件。我错过了什么吗?
loopActive
this
ES6React.Component不会自动将方法绑定到自身。您需要自己将它们绑定在constructor. 像这样:
React.Component
constructor
constructor (props){ super(props); this.state = { loopActive: false, shuffleActive: false, }; this.onToggleLoop = this.onToggleLoop.bind(this); }