问题描述
我将react-select
用于单个选择菜单。当我编辑表单时,defaultValue
似乎正确显示,但是当我提交表单时,如果选择保持不变,则返回的值为undefined
。如果我单击defaultValue
,则提交后它可以正常工作。我是否缺少通过提交来维持prop
的{{1}}?
代码如下:
defaultValue
<Select
closeMenuOnSelect={true}
options={options()}
defaultValue={defaultVal}
className="basic-single"
classNamePrefix="select"
/>
是用于格式化数据的简单函数,
options()
然后 const options = [
{ value: "chocolate",label: "Chocolate" },{ value: "strawBerry",label: "StrawBerry" },{ value: "vanilla",label: "Vanilla" }
];
通过过滤defaultVal
返回一个值:
options
解决方法
由于您使用的是react-hook-form
,因此需要利用其Controller
组件在表单中注册您的选择。参考此处:Integrating Controlled Inputs。
以下组件声明说明了将react-select
组件包装在react-hook-form
控制器组件中。它使用control={control}
在react-hook-form中注册,然后通过Controller组件的呈现道具呈现选择。
您还需要通过更改时调用react-hook-form
来通知handleChange
。 handleChange()
依次使用更改后的值调用react-hook-form
的{{1}},并用setValue()
标记更改。
shouldDirty: true
此处的工作沙箱:https://codesandbox.io/s/react-select-with-react-hook-form-im9hi
const handleChange = (change) => {
setValue("controlledSelect",change,{
shouldDirty: true
});
};
这是一个粗略的片段,显示了有效的选择。似乎您想将import React from "react";
import { useForm,Controller } from "react-hook-form";
import Select from "react-select";
function ControlledSelect() {
const { handleSubmit,control,setValue } = useForm();
const [options,setOptions] = React.useState(initialOptions);
const onSubmitData = (data) => {
console.log(data);
};
const handleChange = (change) => {
setValue("controlledSelect",{
shouldDirty: true
});
};
return (
<div className="container">
<form onSubmit={handleSubmit(onSubmitData)}>
<Controller
name="controlledSelect"
control={control}
defaultValue={options[1]}
render={() => (
<Select
options={options}
defaultValue={options[1]}
onChange={handleChange}
/>
)}
/>
<button type="submit">Submit Select</button>
</form>
</div>
);
}
声明为数组defaultValue
中的索引。这将需要在渲染之前生成格式化的选项数组,而不是传递函数,这可能会更好。
defaultValue={defaultVal[0]}