react-hook-form 已正确设置,我正在使用 defaultValues
我正在尝试使用 html 5 和列表作为下拉框
但是“1”的状态出现在框中,而不是相关的选项文本。
稍微做作的示例,选择被抽象为输入控件
//comes from state management
const item={
"body": "body b",
"subject": "subject b",
"id": "2",
"status": 1,
"result": 2
}
const status: [
{ "key": 0,"text": "pending"},
{ "key": 1,"text": "in progress"},
{ "key": 2,"text": "completed"},
{ "key": 3,"text": "cancelled"}
]
const {
control,
formState: { errors },
handleSubmit,
reset,
} = useForm({
resolver,
});
const attributes={control,errors};
useEffect(() => {
if (!isEmpty(item)) {
reset(item);
}
}, [item]);
const { field,fieldState } = useController(props);
return(
<>
<form onSubmit={handleSubmit(onSubmit)}>
<Input name="id" {...attributes} /> //goes to an abstracted control, working fine
{/*
i want "in progress" to display instead of "1".
yes i know <select/> is an option
*/}
<datalist id={`statusList`}>
{status.map((option) => (
<option key={option.key} value={option.text} data-value={option.key} />
))}
</datalist>
</>
)
请使用此代码:
import React, { useEffect } from 'react';
import { useForm, useController } from 'react-hook-form';
const item = {
body: 'body b',
subject: 'subject b',
id: '2',
status: 1,
result: 2
};
const statuses = [
{ key: 0, text: 'pending' },
{ key: 1, text: 'in progress' },
{ key: 2, text: 'completed' },
{ key: 3, text: 'cancelled' }
];
function Input({ name, control, defaultValue, options }) {
const {
field,
fieldState: { error }
} = useController({
name,
control,
defaultValue
});
return (
<div>
<select {...field}>
{options.map(option => (
<option key={option.key} value={option.key}>
{option.text}
</option>
))}
</select>
{error && <span>{error.message}</span>}
</div>
);
}
function App() {
const { control, formState: { errors }, handleSubmit, reset } = useForm({
defaultValues: item
});
useEffect(() => {
if (item) {
reset(item);
}
}, [item, reset]);
const onSubmit = data => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Input
name="status"
control={control}
defaultValue={item.status}
options={statuses}
/>
<button type="submit">Submit</button>
</form>
);
}
export default App;