你好,我有这段代码,它是一个用于在 React js 中添加联系人的简单项目,我的问题是当我尝试添加新联系人时出现以下错误
未捕获的运行时错误:
错误 undefined 不是一个对象(评估 'e.target.element.contactName')
import React from "react";
class AddContact extends React.Component {
constructor(props) {
super(props);
this.state = {
errorMessage: undefined,
successMessage: undefined,
};
}
handleAddContactFromSubmit = (e) => {
e.preventDefault();
const name = e.target.element.contactName.value.trim();
const email = e.target.element.contactEmail.value.trim();
const phone = e.target.element.contactPhone.value.trim();
this.props.handleAddContact({ name: name, email: email, phone: phone });
};
render() {
return (
<div className="border col-12 text-white p-2">
<form onSubmit={this.handleAddContactFromSubmit}>
<div className="row p-2">
<div className="col-12 text-white-50">Add a new Contact</div>
<div className="col-12 col-md-4 p-1">
<input
className="from-control form-control-sm"
placeholder="Name..."
name="contactName"
></input>
</div>
<div className="col-12 col-md-4 p-1">
<input
className="from-control form-control-sm"
placeholder="Email..."
name="contactEmail"
></input>
</div>
<div className="col-12 col-md-4 p-1">
<input
className="from-control form-control-sm"
placeholder="Phone..."
name="contactPhone"
></input>
</div>
<div className="col-12 col-md-6 offset-md-3 p-1">
<button className="btn btn-primary btn-sm form-control ">
Create
</button>
</div>
</div>
</form>
</div>
);
}
}
export default AddContact;
您需要使用
elements
而不是element
例如:
const name = e.target.elements.contactName.value.trim();