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


当前回答

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

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

}

其他回答

有几种方法。

一是添加 这一点。ontogglloop = this. ontogglloop .bind(this);在构造函数中。

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

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

这样写你的函数:

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

胖箭头功能

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

如果你正在使用babel,你使用ES7绑定操作符绑定'this' https://babeljs.io/docs/en/babel-plugin-transform-function-bind#auto-self-binding

export default class SignupPage extends React.Component {
  constructor(props) {
    super(props);
  }

  handleSubmit(e) {
    e.preventDefault(); 

    const data = { 
      email: this.refs.email.value,
    } 
  }

  render() {

    const {errors} = this.props;

    return (
      <div className="view-container registrations new">
        <main>
          <form id="sign_up_form" onSubmit={::this.handleSubmit}>
            <div className="field">
              <input ref="email" id="user_email" type="email" placeholder="Email"  />
            </div>
            <div className="field">
              <input ref="password" id="user_password" type="new-password" placeholder="Password"  />
            </div>
            <button type="submit">Sign up</button>
          </form>
        </main>
      </div>
    )
  }

}

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

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

在我的例子中,对于使用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} } />
})