admin管理员组文章数量:1315033
I am trying to capture onChange event of the input and calling setState with the new value, but as soon as I type in the input I get:
Uncaught TypeError: Cannot read property 'setState' of undefined
Even though I have called
this.handleChange.bind(this)
in the constructor
index.js
import React from 'react'
import * as ReactDOM from "react-dom";
import App from './App'
ReactDOM.render(
<App />,
document.getElementById('root')
);
App.js
import * as React from "react";
export default class App extends React.Component {
constructor(props) {
super(props)
this.handleChange.bind(this)
this.state = {contents: 'initialContent'}
}
handleChange(event) {
this.setState({contents: event.target.value})
}
render() {
return (
<div>
Contents = {this.state.contents}
<input type="text" onChange={this.handleChange}/>
</div>
);
}
}
I am trying to capture onChange event of the input and calling setState with the new value, but as soon as I type in the input I get:
Uncaught TypeError: Cannot read property 'setState' of undefined
Even though I have called
this.handleChange.bind(this)
in the constructor
index.js
import React from 'react'
import * as ReactDOM from "react-dom";
import App from './App'
ReactDOM.render(
<App />,
document.getElementById('root')
);
App.js
import * as React from "react";
export default class App extends React.Component {
constructor(props) {
super(props)
this.handleChange.bind(this)
this.state = {contents: 'initialContent'}
}
handleChange(event) {
this.setState({contents: event.target.value})
}
render() {
return (
<div>
Contents = {this.state.contents}
<input type="text" onChange={this.handleChange}/>
</div>
);
}
}
Share
Improve this question
asked Dec 29, 2016 at 11:29
simplfuzzsimplfuzz
12.9k25 gold badges88 silver badges140 bronze badges
1 Answer
Reset to default 14Assign this.handleChange.bind(this)
(bind - returns new reference to function) to this.handleChange
., because this.handleChange
have to refer to new function which returns .bind
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.state = {contents: 'initialContent'}
}
本文标签: javascriptReactjsquotthisquot undefined even after bindingStack Overflow
版权声明:本文标题:javascript - React.js - "this" undefined even after binding - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741961826a2407322.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论