patternjavascriptreactCritical
React: "this" is undefined inside a component function
Viewed 0 times
undefinedfunctionreactinsidethiscomponent
Problem
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 (
);
}
onToggleLoop(event) {
// "this is undefined??" <--- here
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}I want to update
loopActive state on toggle, but this object is undefined in the handler. According to the tutorial doc, I this should refer to the component. Am I missing something?Solution
ES6
React.Component doesn't auto bind methods to itself. You need to bind them yourself in constructor. Like this:constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}Code Snippets
constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}Context
Stack Overflow Q#33973648, score: 284
Revisions (0)
No revisions yet.