我正在使用reactjs创建一个crud应用程序。当我尝试验证时,它没有得到验证,也没有得到任何结果。请有人说一些有价值的验证建议。我只是个初学者。
程序如下:
valid= () =>{
if(document.validation.fn.value==="")
{
alert("Enter your first name");
return false;
}
if(document.validation.ln.value==="")
{
alert(" Enter your last name ");
return false;
}
if(document.validation.dn.value==="")
{
alert("Enter your dob");
return false;
}
return true;
};
return (
<div>
<form name="validation" method="POST" onsubmit="return valid()">
Fname: <input
name="fn"
className={this.props.className}
onChange={this._handleChange}
onKeyDown={this._handleKeyDown}
placeholder="First Name"
value={this.state.fname}
/>
Lname: <input
name="ln"
className={this.props.className}
onChange={this._handleChange1}
onKeyDown={this._handleKeyDown1}
placeholder="Last Name"
value={this.state.lname}
/>
DOb: <input
name="dn"
type="Date"
className={this.props.className}
onChange={this._handleChange2}
onKeyDown={this._handleKeyDown2}
placeholder="DOB"
value={this.state.dob}
/>
</form>
</div>
);
答案 0 :(得分:2)
根据您的代码检查我的示例:https://codesandbox.io/s/v3qwvyxmql
主要思想是使用本地状态作为保存数据的临时位置,验证方法应使用本地状态进行验证
class App extends React.Component {
constructor() {
super();
this.state = {
fname: "first name",
lname: "last name",
dob: "dob"
};
}
valid() {
const { fname, lname, dob } = this.state;
if (fname === "") {
alert("Enter your first name");
return false;
}
if (lname === "") {
alert(" Enter your last name ");
return false;
}
if (dob === "") {
alert("Enter your dob");
return false;
}
return true;
}
handleChange = (e, name) => {
this.setState({
[name]: e.target.value
});
};
handleSubmit = e => {
e.preventDefault();
if (!this.valid()) return false;
console.log("Valid");
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
Fname:{" "}
<input
name="fn"
type="text"
onChange={e => this.handleChange(e, "fname")}
placeholder="First Name"
value={this.state.fname}
/>
Lname:{" "}
<input
name="ln"
type="text"
onChange={e => this.handleChange(e, "lname")}
placeholder="Last Name"
value={this.state.lname}
/>
DOb:{" "}
<input
name="dn"
type="text"
onChange={e => this.handleChange(e, "dob")}
placeholder="DOB"
value={this.state.dob}
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
}