React: “this” is undefined inside a component function

前端 未结 10 2272
春和景丽
春和景丽 2020-11-22 04:59
class PlayerControls extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      loopActive: false,
      shuffleActive: false,
    }         


        
10条回答
  •  我寻月下人不归
    2020-11-22 05:51

    You should notice that this depends on how function is invoked ie: when a function is called as a method of an object, its this is set to the object the method is called on.

    this is accessible in JSX context as your component object, so you can call your desired method inline as this method.

    If you just pass reference to function/method, it seems that react will invoke it as independent function.

    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
    

提交回复
热议问题