如何使用 react-hook-form 和 material UI

How to use react-hook-form with props and material UI

我正在使用 Material UI Select 作为可重复使用的组件,我想通过从 parent 传递道具来使用 react-hook-form 验证它到 child 组件。到目前为止,我已经尝试使用 RHF,并将一些道具传递给 child,但是当我选择 select 时,错误不会消失。这是我的代码

import React from 'react';
import styled from '@emotion/styled';
import { Select, MenuItem } from '@material-ui/core';
import { ASSelect } from '../../ASSelect';
import { Controller, useForm } from 'react-hook-form';

const { register, handleSubmit, watch, errors, control, setValue } = useForm();
  const onSubmit = (data: any) => {
    console.log(errors);
  };
  
const defaultDashboard = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];
  
const Parent = () => {
  return (
    <Controller
          as={
            <ASSelect
              menuItems={defaultDashboard}
              label="Default dashboard*"
              handleChange={dashboardHandler}
              value={dashboardValue}
          }
          name="Select"
          control={control}
          rules={{ required: true }}
          onChange={([selected]) => {
            return { value: selected };
          }}
        />
        {errors.Select ? <span>Default dashboard is required</span> : null}
    )
 }

export {Parent};

const ASSelect = ({menuItems, label, handleChange, value}) => {
  return (
    <div>
      <Select>
      {menuItems.map((el, index)=> {
        return <MenuItem key={index}>{el.label}</MenuItem>
      }}
    </Select>
    </div>
  )}
  
 export {ASSelect};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

因此,当我在没有 select 任何内容的情况下提交表单时,会弹出错误消息。但是当我select一个选项时,错误会一直存在。我做错了什么?

您可以通过以下方式将 Select 与 react-hook-forms 中的 Controller 一起使用:

const SelectController = ({ name, menuItems, control }) => (
  <Controller
    as={
      <Select>
        {menuItems.map(({ value, label }, index) => (
          <MenuItem key={index} value={value}>
            {label}
          </MenuItem>
        ))}
        }
      </Select>
    }
    name={name}
    control={control}
    defaultValue=""
    rules={{ required: true }}
  />
);

或将 Select 与 react-hook-forms 中的 setValue 一起使用,如下所示:

const SelectSetValue = ({ name, menuItems, setValue }) => {
  return (
    <Select
      name={name}
      defaultValue=""
      onChange={e => setValue(name, e.target.value)}
    >
      {menuItems.map(({ value, label }, index) => (
        <MenuItem key={index} value={value}>
          {label}
        </MenuItem>
      ))}
      }
    </Select>
  );
};

在这两种情况下,您最初都会收到错误验证 onSubmit 事件。当您 select 一个值时 SelectControllerSelectSetValue 当您 select 一个值并重新触发 onSubmit 时,错误显示将在之后更新。

您可以在 link:
之后查看工作示例 https://codesandbox.io/s/somaterialselecthookform-kdext?file=/src/App.js