react-hook-form 带有受控输入、是的验证、材质 UI 组件、setValue
import React from 'react';
import {useForm, Controller} from 'react-hook-form';
import {yupResolver} from '@hookform/resolvers/yup';
import Autocomplete from '@material-ui/lab/Autocomplete';
import { TextField } from '@material-ui/core';
import * as yup from 'yup';
const schema = yup.object().shape({
firstname: yup.string().required(),
buyer: yup.string().required(),
});
const UserForm = () => {
const {
watch,
setValue,
register,
handleSubmit,
control,
formState: {errors},
} = useForm({
defaultValues: {
item: {"id":2,"name":"item2"},
},
resolver: yupResolver(schema),
});
const itemList = [
{id: 1, name: 'item1'},
{id: 2, name: 'item2'},
];
return (
<div
style={{
margin: '200px',
}}>
<form onSubmit={handleSubmit(d => console.table(d))}>
<Controller
control={control}
name="item"
rules={{required: true}}
render={({field: {onChange, value}}) => (
<Autocomplete
onChange={(event, item) => {
onChange(item);
}}
value={value}
options={itemList}
getOptionLabel={item => (item.name ? item.name : '')}
getOptionSelected={(option, value) =>
value === undefined || value === '' || option.id === value.id
}
renderInput={params => (
<TextField
{...params}
label="items"
margin="normal"
variant="outlined"
error={!!errors.item}
helperText={errors.item && 'item required'}
/>
)}
/>
)}
/>
<input type="submit" />
<button
onClick={() => {
setValue('item', {id: 2, name: 'item2'});
}}>
setValue
</button>
<h6>data from register</h6>
{<pre>{JSON.stringify(watch())}</pre>}
</form>
</div>
);
};
export default UserForm;