如何将react-hook-form与ant design或material UI一起使用

2024-02-18

我正在尝试使用react-hook-form库来验证表单。当我使用 ant design 或 Material UI 渲染视图时,它无法正常工作。

<Input name="firstName" ref={register({ required: true })} />
  {errors.firstName && 'First name is required'}

发生了一些警告:"Missing name at.....".


在此处对作者进行反应钩子。 React Hook Form 包含不受控制的组件和本机输入,但是很难避免与外部受控组件(例如 React-Select、AntD 和 Material-UI)一起使用。因此,我构建了一个包装器组件来帮助您更轻松地集成。

https://github.com/react-hook-form/react-hook-form-input https://github.com/react-hook-form/react-hook-form-input

好吧,你可能想知道这样做的意义是什么,以及你从带有受控组件的 React hook 形式中得到了什么?首先,您仍然可以根据自己的选择从我们的构建验证或模式验证中受益。其次,这将通过将输入状态更新隔离到自身来提高您的应用程序或表单性能,这意味着即使使用受控组件,您的表单根也可以通过 0 重新渲染来实现。

这是codesandbox示例:https://codesandbox.io/s/react-hook-form-hookforminput-rzu9s https://codesandbox.io/s/react-hook-form-hookforminput-rzu9s

希望这些是有意义的,并且我创建的额外组件也能帮助您。

除此之外,我还构建了一个包装器组件以使事情变得更容易一些:

import React from 'react';
import useForm from 'react-hook-form';
import { RHFInput } from 'react-hook-form-input';
import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

function App() {
  const { handleSubmit, register, setValue, reset } = useForm();

  return (
    <form onSubmit={handleSubmit(data => console.log(data))}>
      <RHFInput
        as={<Select options={options} />}
        rules={{ required: true }}
        name="reactSelect"
        register={register}
        setValue={setValue}
      />
      <button
        type="button"
        onClick={() => {
          reset({
            reactSelect: '',
          });
        }}
      >
        Reset Form
      </button>
      <button>submit</button>
    </form>
  );
}

https://github.com/react-hook-form/react-hook-form-input https://github.com/react-hook-form/react-hook-form-input


update

React-hook-form v4、react-hook-form-input 已合并到主存储库中并重命名为 Controller。

https://react-hook-form.com/api#Controller https://react-hook-form.com/api#Controller

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将react-hook-form与ant design或material UI一起使用 的相关文章

随机推荐