Javascript React.js-“反应”;这";绑定后仍未定义
我试图捕获输入的onChange事件,并使用新值调用setState,但一旦输入,我就会得到:Javascript React.js-“反应”;这";绑定后仍未定义,javascript,reactjs,this,bind,Javascript,Reactjs,This,Bind,我试图捕获输入的onChange事件,并使用新值调用setState,但一旦输入,我就会得到: Uncaught TypeError: Cannot read property 'setState' of undefined 即使我打过电话 this.handleChange.bind(this) 在构造函数中 index.js import React from 'react' import * as ReactDOM from "react-dom"; import App from
Uncaught TypeError: Cannot read property 'setState' of undefined
即使我打过电话
this.handleChange.bind(this)
在构造函数中
index.js
import React from 'react'
import * as ReactDOM from "react-dom";
import App from './App'
ReactDOM.render(
<App />,
document.getElementById('root')
);
从“React”导入React
从“react dom”导入*作为react dom;
从“./App”导入应用程序
ReactDOM.render(
,
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>
);
}
}
import*as React from“React”;
导出默认类App扩展React.Component{
建造师(道具){
超级(道具)
this.handleChange.bind(this)
this.state={contents:'initialContent'}
}
手变(活动){
this.setState({contents:event.target.value})
}
render(){
返回(
Contents={this.state.Contents}
);
}
}
将this.handleChange.bind(this)
(bind-返回对函数的新引用)分配给this.handleChange
,因为this.handleChange
必须引用返回的新函数
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.state = {contents: 'initialContent'}
}