[英]How to use react-hook-form with props and material UI
我正在使用 Material UI Select 作為可重用組件,我想通過從父組件傳遞道具到子組件來使用 react-hook-form 驗證它。 到目前為止,我已經嘗試從 RHF 使用,並將一些道具傳遞給孩子,但是當我選擇 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 時,錯誤會一直存在。 我究竟做錯了什么?
您可以通過以下方式將來自 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 }}
/>
);
或使用 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 一個值和SelectSetValue
當您 select 一個值並重新觸發 onSubmit 時,將更新SelectController
的錯誤顯示。
您可以通過以下鏈接查看工作示例:
https://codesandbox.io/s/somaterialselecthookform-kdext?file=/src/App.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.