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状态,但该对象在处理程序中未定义。根据教程文档,我这应该是指组件。我遗漏了什么吗?


当前回答

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

其他回答

这样写你的函数:

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

胖箭头功能

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

在我的例子中,对于使用forwardRef接收ref的无状态组件,我必须做这里所说的https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd

从这个(onClick没有访问'this'的等价物)

const Com = forwardRef((props, ref) => {
  return <input ref={ref} onClick={() => {console.log(ref.current} } />
})

这(它工作)

const useCombinedRefs = (...refs) => {
  const targetRef = React.useRef()

  useEffect(() => {
    refs.forEach(ref => {
      if (!ref) return

      if (typeof ref === 'function') ref(targetRef.current)
      else ref.current = targetRef.current
    })
  }, [refs])

  return targetRef
}

const Com = forwardRef((props, ref) => {
  const innerRef = useRef()
  const combinedRef = useCombinedRefs(ref, innerRef)

  return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
})

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

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

我还用过:

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

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

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

你可以重写如何从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文档显示了从属性中的表达式调用函数时的这种模式。