使用它作为参考,react.js - show a message on and after form submission,我试图复制类似的东西,但我在控制台中遇到错误,"未捕获的TypeError:无法读取属性' setState'未定义"。我无法确定我在哪里丢失了这个'这个'在我的州组成部分。
import React from 'react'
import RadarInput from './radarInput'
class RadarForm extends React.Component {
constructor(props) {
super(props);
}
onFormSubmit = (data, cb) => {
cb(data);
}
render() {
return (
<div>
<RadarInput OnRadarSubmit={this.onFormSubmit.bind(this)} />
</div>
)
}
}
export default RadarForm
import React from 'react'
class RadarInput extends React.Component {
constructor(props) {
super(props);
this.state = {value:"Hello!", message: ''}
}
handleChange = (evt) => {
this.setState({value: evt.target.value });
}
sendContent = function(e) {
console.log("I'm in content")
console.log("this is e: ", this.state.value);
e.preventDefault();
var radarNum = this.state.value
this.setState({value: '', message: 'Please wait ...'});
this.props.OnRadarSubmit({
value: radarNum
}, function(data){
console.log("data in cb ", data.value);
this.setState({ message: data.value });
});
}
render() {
return (
<div>
Title: <div>{this.state.message}</div>
<form onSubmit={this.sendContent.bind(this)}>
Radar Number: <input type="text" value={this.state.value} onChange={this.handleChange.bind(this)} />
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
export default RadarInput
答案 0 :(得分:2)
您需要先将this
设置为OnRadarSubmit()
回调之外的变量。
var self = this;
this.props.OnRadarSubmit({ value: radarNum}, function(data){
console.log("data in cb ", data.value);
self.setState({ message: data.value });
});
原因是在回调中,this
不再引用类范围,因此通过设置self
,您明确使用了封闭范围。