我将Material UI Select用作可重用组件,并且我想通过将props从父组件传递到子组件来使用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>
因此,当我提交表单而不选择任何内容时,将弹出错误。但是,当我选择一个选项时,错误将仍然存在。我在做什么错了?
答案 0 :(得分:2)
您可以通过以下方式从react-hook-forms中将Select与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 }}
/>
);
或按以下方式从react-hook-forms中与setValue
一起使用Select:
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