我正在使用React Hook Form
以验证一些简单的输入:
import React from "react";
import useForm from "react-hook-form";
import "./App.css";
function App() {
const { register, handleSubmit, errors } = useForm();
const onSubmit = data => {
console.log(data);
};
return (
<div className="App">
<header className="App-header">
<form onSubmit={handleSubmit(onSubmit)}>
<input
className="mkn-input"
name="firstName"
placeholder="First name"
ref={register({
required: true,
maxlength: 20,
message: "invalid first name"
})}
/>
<span> {errors.firstName && errors.firstName.message}</span>
<input
placeholder="Last name"
className="mkn-input"
name="lastName"
ref={register({
pattern: /^[A-Za-z]+$/i,
message: "Invalid last name"
})}
/>
{errors.lastName && <span> errors.lastName.message</span>}
<input
name="age"
type="number"
placeholder="Age"
className="mkn-input"
ref={register({ min: 18, max: 99 })}
/>
<input type="submit" className="mkn-btn" />
</form>
</header>
</div>
);
}
export default App;
但是我在显示 DOM 中的错误时遇到了一个奇怪的问题,我也尝试在控制台中记录它们但没有成功,我错过了什么?
完整代码: