You*_*dna 6 validation reactjs react-component react-hook-form
我使用以下代码创建带有表单验证的登录页面:
import React from 'react';
import { Button, Form, FormGroup, Label, Input } from 'reactstrap';
import { useForm } from 'react-hook-form';
class SignIn extends React.Component {
const { register, handleSubmit, errors } = useForm();
const onSubmit = data => console.log(data);
console.log(errors);
render() {
return (
<div>
<Form onSubmit={handleSubmit(onSubmit)}>
<Label>Email : </Label>
<Input type="email" placeholder="email" name="email" ref={register({required: true, pattern: /^\S+@\S+$/i})}></Input>
<Label>Password : </Label>
<Input type="password" placeholder="password" name="password" ref={register({required: true, min: 8, maxLength: 20})}></Input>
</Form>
</div>
);
}
}
export default SignIn;
Run Code Online (Sandbox Code Playgroud)
我在类组件中使用react-hook-form时遇到问题
我的问题(如果可能的话)是:如何在类组件中使用react-hook-form而不将代码重写为钩子版本?
小智 7
您不能在 React 类组件中使用钩子。您提供的类看起来很小,我认为您可以轻松地将其重写为功能组件。也许您不想,您可以提供 hoc 来包装您的类组件。
export const withUseFormHook = (Component) => {
return props => {
const form = useForm();
return <Component {...props} {...form} />
}
}
Run Code Online (Sandbox Code Playgroud)
在您的 SignIn 组件中只需执行以下操作:
export default withUseFormHook(SignIn);
Run Code Online (Sandbox Code Playgroud)
小智 2
最好和最简单的方法是将类 Component 更改为功能组件并使用 useForm 挂钩。您可以在下面找到示例代码:
import React from 'react'
import { Button, Form, FormGroup, Label, Input } from 'reactstrap';
import { useForm } from 'react-hook-form';
const SignIn = () => {
const { register, handleSubmit, errors } = useForm();
const onSubmit = data => console.log(data);
console.log(errors);
return (
<>
<div>
<Form onSubmit={handleSubmit(onSubmit)}>
<Label>Email : </Label>
<Input type="email" placeholder="email" name="email" ref={register({required: true, pattern: /^\S+@\S+$/i})}></Input>
<Label>Password : </Label>
<Input type="password" placeholder="password" name="password" ref={register({required: true, min: 8, maxLength: 20})}></Input>
</Form>
</div>
</>
)}
export default SignIn;
Run Code Online (Sandbox Code Playgroud)