React:“this”在组件函数中未定义

2022-08-30 01:16:48
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()
  }

我想在切换时更新状态,但对象在处理程序中未定义。根据教程文档,我应该参考该组件。我错过了什么吗?loopActivethisthis


答案 1

ES6 不会自动将方法绑定到自身。您需要在 中自行绑定它们。喜欢这个:React.Componentconstructor

constructor (props){
  super(props);
  
  this.state = {
      loopActive: false,
      shuffleActive: false,
    };
  
  this.onToggleLoop = this.onToggleLoop.bind(this);

}

答案 2

有几种方法。

一种是添加构造函数。this.onToggleLoop = this.onToggleLoop.bind(this);

另一个是箭头函数。onToggleLoop = (event) => {...}

然后是.onClick={this.onToggleLoop.bind(this)}