当用户点击提交按钮时,我需要将这些输入字段绑定到Message接口的实例,为此我在类中创建了一个Message对象
并在表单中设置输入值的值(keepNameUpdated())。
当我输入内容时,它会抛出
未捕获的TypeError:无法读取未定义的属性“消息”
所以它说“这个”是未定义的,但为什么呢?
这是我的代码:
export class IMessage {
Name: string;
Surname: string;
}
export default class Contact extends React.Component<IContactProperties, IWebPartState> {
message : IMessage;
constructor(props: IContactProperties, state: IWebPartState) {
super(props);
this.message = new IMessage();
}
public render(): JSX.Element {
return (
<div className="row">
<div className="form-group col-md-6">
<label >Name</label>
<input type="text" className="form-control" onChange={this.keepNameUpdated} id="name" placeholder="Adiniz" />
</div>
<div className="form-group col-md-6">
<label >Surname</label>
<input type="text" className="form-control" id="surname" placeholder="Soyadiniz" />
</div>
<div className="form-group col-md-12">
<button type="button" className="btn btn-success" onClick={this.clickSubmit}><i className="fa fa-save"></i> Submit</button>
</div>
</div>
);
}
private keepNameUpdated(e) {
this.message.Name=e.target.value;
}
private keepSurnameUpdated(e) {
this.message.Surname=e.target.value;
}
答案 0 :(得分:1)
this
概念引用React组件的实例。因此,在构造函数中,添加以下行:
this.keepNameUpdated = this.keepNameUpdated.bind(this);
this.keepSurnameUpdated = this.keepSurnameUpdated.bind(this);