debugjavascriptreactCritical
Unable to access React instance (this) inside event handler
Viewed 0 times
instanceunableaccessreactinsideeventhandlerthis
Problem
I am writing a simple component in ES6 (with BabelJS), and functions
Typical errors include something like
Cannot read property 'setState' of undefined
or
this.setState is not a function
Do you know why? Here is the code:
this.setState is not working. Typical errors include something like
Cannot read property 'setState' of undefined
or
this.setState is not a function
Do you know why? Here is the code:
import React from 'react'
class SomeClass extends React.Component {
constructor(props) {
super(props)
this.state = {inputContent: 'startValue'}
}
sendContent(e) {
console.log('sending input content '+React.findDOMNode(React.refs.someref).value)
}
changeContent(e) {
this.setState({inputContent: e.target.value})
}
render() {
return (
The input form is here:
Title:
Submit
)
}
}
export default SomeClassSolution
this.changeContent needs to be bound to the component instance via this.changeContent.bind(this) before being passed as the onChange prop, otherwise the this variable in the body of the function will not refer to the component instance but to window. See Function::bind.When using
React.createClass instead of ES6 classes, every non-lifecycle method defined on a component is automatically bound to the component instance. See Autobinding.Be aware that binding a function creates a new function. You can either bind it directly in render, which means a new function will be created every time the component renders, or bind it in your constructor, which will only fire once.
constructor() {
this.changeContent = this.changeContent.bind(this);
}
vs
render() {
return ;
}
Refs are set on the component instance and not on
React.refs: you need to change React.refs.someref to this.refs.someref. You'll also need to bind the sendContent method to the component instance so that this refers to it.Context
Stack Overflow Q#29577977, score: 270
Revisions (0)
No revisions yet.