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