我是React
的新手,我目前正在学习如何制作预约风格的网络应用,但是有一个我不太明白如何修复的错误。
错误是:
未捕获的TypeError:无法读取未定义的属性'onUserInput'
相关代码是约会comp,作为父组件,约会形式comp作为子组件。
当AppointmentForm
尝试从onUserInput
方法调用handleChange
时,会发生错误。对我来说,错误听起来像我没有正确调用方法,但我还没有找到解决方法。任何帮助将不胜感激,谢谢
class Appointments extends React.Component {
constructor(props)
{
super(props);
this.state = {
appointments: this.props.appointments,
input_title: "Team Startup Meeting",
input_apt_time: 'Tomorrow at 9am'
};
}
handleUserInput(obj)
{
this.setState(obj);
}
handleFormSubmit()
{
var appointment = {title: this.state.title,
apt_time: this.state.apt_time}
$.post('/appointments',
{appointment: appointment});
}
render()
{
return (
<div>
<AppointmentForm input_title={this.state.input_title}
input_apt_time={this.state.input_apt_time}
onUserInput={this.handleUserInput} />
<AppointmentsList appointments={this.props.appointments}
onFormSubmit={this.handleFormSubmit}/>
</div>
);
}
}
class AppointmentForm extends React.Component {
handleChange(e)
{
var name = e.target.name;
obj = new Object();
obj.name = e.target.value;
this.props.onUserInput(obj);
}
handleSubmit(e)
{
e.preventDefault();
this.props.onFormSubmit();
}
render()
{
return (
<div>
<h2>Make an Appointment</h2>
<form onSubmit={this.handleSubmit.bind(this)}>
<input name="title" placeholder="Appointment Title"
value={this.props.input_title}
onChange={this.handleChange}/>
<input name="apt_time" placeholder="Date and Time"
value={this.props.input_apt_time}
onChange={this.handleChange} />
<input type="submit" value="Make Appointment" />
</form>
</div>
)
}
}
答案 0 :(得分:1)
您应该在组件构造函数中将组件实例绑定到this
方法的handleChange
:
class AppointmentForm extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
..........
}