[英]React.js - “this” undefined even after binding
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: 我试图捕获输入的onChange事件并使用新值调用setState ,但是一旦输入输入,我得到:
Uncaught TypeError: Cannot read property 'setState' of undefined
Even though I have called 即使我打过电话
this.handleChange.bind(this)
in the constructor 在构造函数中
index.js index.js
import React from 'react'
import * as ReactDOM from "react-dom";
import App from './App'
ReactDOM.render(
<App />,
document.getElementById('root')
);
App.js 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>
);
}
}
Assign 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
将
this.handleChange.bind(this)
赋值( bind - 返回对函数的新引用 )赋予this.handleChange
。,因为this.handleChange
必须引用返回.bind
新函数
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.state = {contents: 'initialContent'}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.