Codesandbox:https://codesandbox.io/p/sandbox/codesandboxer-example-forked-mypffg?file=%2Fexample.tsx%3A105%2C44
我有一个
react-select
异步组件向 API 发出请求。我想在react-hook-form字段中显示结果对象的各个字段。当我使用 RHF 注册这些字段时,它们可以成功写入表单状态,但似乎没有对此做出反应。无论我使用异步组件还是显式 setValue
调用设置表单状态,输入都不会显示值。
我尝试在示例中同时使用
register
和 input
来包装 Controller
,但都没有响应表单状态的更新input
const formMethods = useForm<FormFields>({
defaultValues: {
todo: {
title: "",
id: "",
},
},
});
return (
<div className="row">
<Controller
control={formMethods.control}
name={"todo"}
render={(params) => (
<AsyncCreatableSelect
defaultOptions
getOptionLabel={(todo) => todo.title}
getOptionValue={(todo) => todo.id}
loadOptions={promiseOptions}
{...params.field}
/>
)}
/>
<div>
<Controller
control={formMethods.control}
name={"todo.id"}
render={(params) => {
return (
<label>
Controller-bound
<input {...params.field} value={params.field.value} />
</label>
);
}}
/>
</div>
<label>
Register-bound
<input {...formMethods.register("todo.title")} />
</label>
<div>
<button
onClick={() => {
formMethods.setValue(
"todo",
{
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false,
},
{ shouldDirty: true, shouldTouch: true }
);
}}
>
Set Object Value
</button>
</div>
</div>
这会触发字段更新