如何在蚂蚁设计或材质 UI 中使用 react-hook-form

San*_*ang 11 reactjs material-ui antd react-hook-form

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

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

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

Sam*_*hel 22

对于 Material-UI,您可以register通过 TextField 组件道具inputRef(我也使用 Yup 进行验证模式)

import React, { useState } from 'react';
import { Button, TextField } from '@material-ui/core';
import useForm from 'react-hook-form';
import { object, string } from 'yup';

const Form: React.FC = () => {
  const schema = object().shape({
    username: string().required('Username is required'),
    password: string().required('Password is required'),
  });
  const { register, handleSubmit, errors } = useForm({ validationSchema: schema });
  const onSubmit = (data: any) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <TextField
        name="username"
        error={!!errors.username}
        label="Username"
        helperText={errors.username ? errors.username.message : ''}
        type="email"
        inputRef={register}
        fullWidth
      />
      <TextField
        name="password"
        error={!!errors.password}
        label="Password"
        inputRef={register}
        helperText={errors.password ? errors.password.message : ''}
        type="password"
        fullWidth
      />

      <Button
        color="primary"
        type="submit"
        variant="contained"
        fullWidth
      >
        Submit
      </Button>
    </form>
  );
};
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是最好的答案,比使用控制器干净得多。 (2认同)

Bru*_*uce 20

在这里反应钩形作者。React Hook Form 包含不受控制的组件和本机输入,但是很难避免使用外部受控组件,例如 React-Select、AntD 和 Material-UI。所以我构建了一个包装组件来帮助您更轻松地集成。

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

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

这是代码和框示例: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>
  );
}
Run Code Online (Sandbox Code Playgroud)

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


更新

React-hook-form v4,react-hook-form-input 已合并到主 repo 并重命名为 Controller。

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


Cha*_*kin 16

V4 的最新建议是使用内置<Controller />组件 ( docs )。您不需要安装react-hook-form-input.

来自react-hook-form-input的 README.md :

该组件现在是 React Hook Form V4 的一部分,并使用更简单的 API 重命名为 Controller。

例子:

  <Controller
    as={<TextField />}
    name="firstName"
    control={control}
    defaultValue=""
  />
Run Code Online (Sandbox Code Playgroud)

请注意,已接受答案的作者@Bill 现在也表示该答案已过时并“请改用控制器”。


小智 5

使用 inputRef 对 TextField 组件应该足够了,对于任何默认值,react-hook-form ( useForm ) 提供 defaultValue 以防您想使用某些默认值或 material-ui 在其 TextField API 中具有 defaultValue

const { register, handleSubmit, errors, watch } = useForm({ mode: 'onChange' });



<TextField
  inputRef={register({ required: true })}
  label="Email Address"
  name="email"
  type="email"
  autoComplete="email"
  onChange={handleUpdate}
  error={errors.email}
  helperText={errors.email && 'email required'}
/>
Run Code Online (Sandbox Code Playgroud)