No se puede acceder a la instancia de React (this) dentro del controlador de eventos
Estoy escribiendo un componente simple en ES6 (con BabelJS) y funcionesthis.setState
no está trabajando.
Los errores típicos incluyen algo como
No se puede leer la propiedad 'setState' de undefined
o
this.setState no es una función
¿Sabes por qué? Aquí está el código:
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 (
<div>
<h4>The input form is here:</h4>
Title:
<input type="text" ref="someref" value={this.inputContent}
onChange={this.changeContent} />
<button onClick={this.sendContent}>Submit</button>
</div>
)
}
}
export default SomeClass