0

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

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>

因此,当我在未选择任何内容的情况下提交表单时,会弹出错误。但是当我选择一个选项时,错误将仍然存在。我究竟做错了什么?

4

1 回答 1

2

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

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 with setValuefrom react-hook-forms 如下:

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 事件中获得错误验证。SelectController当您选择一个值以及SelectSetValue当您选择一个值并重新触发 onSubmit 时, 错误显示会在之后更新。

您可以通过以下链接查看工作示例:
https ://codesandbox.io/s/somaterialselecthookform-kdext?file=/src/App.js

于 2020-04-23T19:50:56.783 回答