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

其他回答

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

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

}

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

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

你可以重写如何从render()方法调用ontogglloop方法。

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={(event) => this.onToggleLoop(event)}
      spin={this.state.loopActive}
    />       
  </div>
    );
  }

React文档显示了从属性中的表达式调用函数时的这种模式。

您应该注意到,这取决于函数的调用方式 即:当一个函数作为一个对象的方法被调用时,它的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

如果你在生命周期方法中调用你创建的方法,比如componentDidMount…那么你只能用这个。ontogglloop = this. ontooglloop .bind(this)和胖箭头函数ontogglloop = (event) =>{…}。

在构造函数中声明函数的正常方法不起作用,因为生命周期方法在前面被调用。