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); 
 
} 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!