根据文档(https://react-hook-form.com/get-started#IntegratingControlledInputs),我正在尝试使用Controller包装器组件在React Hook窗体中包装React Select
<Controller
name="ShiftCaptain"
control={control}
render={({ field }) => (
<Select
{...field}
value={selectValue}
options={options}
placeholder={"Select Person"}
onChange={(e) => setSelectValue(e)}
/>
)}
/>在表单提交时,React Select中捕获的值不会填充到React Hook表单中:

有什么想法吗?
提亚
发布于 2021-10-13 11:43:41
您在<ReactSelect />组件上传播的render回调的field对象有一个value和一个onChange属性,RHF需要该属性将值链接到它的内部表单状态。现在你覆盖了它,所以RHF不能更新这个值。试一试,它应该是有效的:
<Controller
name="ShiftCaptain"
control={control}
defaultValue={null}
render={({ field }) => (
<Select
{...field}
options={options}
placeholder={"Select Person"}
/>
)}
/>如果您想在页面加载后为select设置默认值,您应该使用<Controller /> defaultValue属性,它会将该值传递给您的<ReactSelect />。
发布于 2021-10-13 00:16:26
请选中此代码沙箱。https://codesandbox.io/s/react-hook-form-v7-controller-forked-40t3s?file=/src/index.js
const handleOnChange = (e) => {
setSelectedValue(e.value);
};
<label>React Select</label>
<Controller
name="ReactSelect"
control={control}
render={({ field }) => (
<ReactSelect
isClearable
{...field}
value={selectedValue}
onChange={handleOnChange}
options={[
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
]}
/>
)}
/>https://stackoverflow.com/questions/69548100
复制相似问题