React-hook-form 字段无法从状态中的对象读取

问题描述 投票:0回答:1

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


reactjs react-hook-form react-select
1个回答
0
投票
https://codesandbox.io/p/sandbox/codesandboxer-example-forked-4q34n8?file=%2Fexample.tsx%3A42%2C15

技巧是显式设置(子)字段:

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>

这会触发字段更新

© www.soinside.com 2019 - 2024. All rights reserved.