javascript - react : "this" is undefined inside a component function

标签 javascript reactjs this

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/

相关文章:

css - React Native - 页脚中心的按钮位置

JavaScript:Promise.all 结果中有 1 个未定义值

javascript - 在node js中调整图像大小

javascript - 从对象数组中获取唯一元素

reactjs - 是否可以禁用 Material-Table 的拖放功能?

c++ - 如果字段通过引用传递,则类字段可以在 const 方法内修改吗?

JavaScript - 处理 'this' 指针和自定义参数的最佳方法

javascript - 需要将 "this"作为参数传递给 global - IIFE 吗?

javascript - 学习angularjs时的存储方法

javascript - Mongoose 在使用 import 语法时未定义,而在使用 require 时未定义