【问题标题】:React Hook Form errors not working with Chakra UIReact Hook Form 错误不适用于 Chakra UI
【发布时间】:2021-04-10 16:57:15
【问题描述】:

我正在尝试使用 ChakraUI 和 React-Hook-Form 来创建我的表单。但是,我的错误不起作用。我试过不使用 chakra ui,但它仍然不起作用。这是我的代码:

import React from 'react'
import { useForm } from "react-hook-form";
import "./App.css"
import { Input } from "@chakra-ui/react"
import { Text } from "@chakra-ui/react"
import {
    Alert,
    AlertIcon,
    AlertTitle,
    AlertDescription,
} from "@chakra-ui/react"


function App() {

    const { register, handleSubmit, errors } = useForm();
    const onSubmit = data => console.log(data);

    return (
        <div className="app-container">
            <form onSubmit={handleSubmit(onSubmit)}>
                <div className="header-container">
                    <Text fontSize="3xl" align="center" className="app-header">Finish the survey</Text>
                </div>
                <div className="email">
                    <Text fontSize="xl">Your Email</Text>
                    <Input name="email" placeholder="Your Email..." type="text" ref={register({ maxLength: { value: 23, message: "test" } })} />
                    {errors.email && (<span>{errors.email.message}</span>)}
                </div>
            </form>
        </div>
    )
}

export default App

【问题讨论】:

  • 您的代码没有问题。它正在工作并且错误正在填充。默认情况下,react-hook-form 仅在提交表单时进行验证。所以输入后按回车键,你会看到它。您可以通过修改 useForm 变量来更改此行为 ` const { register, handleSubmit, errors } = useForm({ mode: 'onChange', reValidateMode: 'onChange' });`

标签: reactjs react-hook-form chakra-ui


【解决方案1】:

不知道你正在使用的库的版本,我不能肯定,但尝试改变

const { register, handleSubmit, errors } = useForm();

const { register, handleSubmit, formState: { errors } } = useForm();

我在图书馆网站主页上按照他们的示例进行操作时遇到了同样的问题,并且已经提交了 PR。

【讨论】:

  • 这解决了我的问题,似乎是 'react-hook-form' 的 v6 和 v7 之间的区别。
猜你喜欢
  • 2022-01-21
  • 2020-12-25
  • 2021-03-20
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
相关资源
最近更新 更多