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


当前回答

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

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

其他回答

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

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);

}

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

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

我还用过:

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

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

如果你正在使用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>
    )
  }

}