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

我想在toggle上更新loopActive状态,但该对象在处理程序中未定义。根据教程文档,我这应该是指组件。我遗漏了什么吗?


当前回答

我在一个渲染函数中遇到了类似的绑定,并以以下方式传递上下文:

{someList.map(function(listItem) {
  // your code
}, this)}

我还用过:

{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}

其他回答

您应该注意到,这取决于函数的调用方式 即:当一个函数作为一个对象的方法被调用时,它的this被设置为该方法被调用的对象。

它可以在JSX上下文中作为组件对象访问,因此您可以像此方法一样内联调用所需的方法。

如果你只是把引用传递给函数/方法,react似乎会把它作为独立的函数调用。

onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined

onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object

我在一个渲染函数中遇到了类似的绑定,并以以下方式传递上下文:

{someList.map(function(listItem) {
  // your code
}, this)}

我还用过:

{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}

在我的情况下,这是解决方案= ()=> {}

methodName = (params) => {
//your code here with this.something
}

ES6反应。组件不会自动将方法绑定到自身。你需要在构造函数中自己绑定它们。是这样的:

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

}

这样写你的函数:

onToggleLoop = (event) => {
    this.setState({loopActive: !this.state.loopActive})
    this.props.onToggleLoop()
}

胖箭头功能

关键字this在胖箭头函数内外的绑定是一样的。这与使用function声明的函数不同,后者可以在调用时将This绑定到另一个对象。维护this绑定对于像映射:this.items这样的操作非常方便。map(x => this.doSomethingWith(x))。