React: “this” is undefined inside a component function

前端 未结 10 2112
春和景丽
春和景丽 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:41

    Write your function this way:

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

    Fat Arrow Functions

    the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).

提交回复
热议问题