我正在编写一个具有表单的React组件,其中包含无线电按钮。我尝试创建可以收集所选按钮值和控制台的值的onChange()和handlesubmit()函数,但尚未识别事件对象,我会收到此错误:
未定义的typeerror:无法读取未定义的属性
为什么会发生这种情况,我现在该怎么办?
这是我的代码:
class NoteInput extends React.Component {
constructor(props) {
super(props);
this.state={
selectedValue: ''
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({selectedValue: e.target.value})
}
handleSubmit(e) {
e.preventDefault();
console.log(this.state.selectedValue);
}
render() {
return (
<div>
<form onChange={this.handleChange()} >
<input type="radio" id="0" name="location" value={this.props.locations[0]} />
<label htmlFor="choice1">Safa Park</label>
<input type="radio" id="1" name="location" value={this.props.locations[1]} />
<label htmlFor="choice2">Mercato</label>
<input type="radio" id="2" name="location" value={this.props.locations[2]} />
<label htmlFor="choice3">Burj Khalifa</label>
</form>
<input onSubmit={this.handleSubmit()} type="submit" value="Submit" />
</div>
);
}
}
您正在调用功能,而不是将它们传递给事件处理程序。因此,通过删除 ()
onChange={this.handleChange}
onSubmit={this.handleSubmit}