reactjs - 如何将 React-Select 中的选定值转发到 react-hook-form
问题描述
我正在使用 react-hook-form 并尝试按照指南从自定义 react-select 组件中获取选定的值:UseFormMethods。
问题是没有值被传递给表单。
我正在执行以下操作:
interface Option {
label: string;
value: string;
}
interface Props {
name: string;
options: Option[];
error?: string;
label?: string;
placeholder?: string;
disabled?: boolean;
clearable?: boolean;
}
const MySelect = React.forwardRef<ReactSelect, Props>(
(
{ name, error, options, label, placeholder, disabled, clearable, ...rest },
ref
) => (
<>
{label && <label htmlFor={name}>{label}</label>}
<ReactSelect
id={name}
name={name}
ref={ref}
options={options}
placeholder={placeholder || ""}
isDisabled={disabled}
isClearable={clearable}
{...rest}
/>
{error && <span>{error}</span>}
</>
)
);
export default MySelect;
代码沙盒中的完整代码。谁能帮我?
解决方案
你考虑过使用Controller
吗?
https://react-hook-form.com/api#Controller
我们实际上在文档上也有一个工作版本:
https://codesandbox.io/s/react-hook-form-v6-controller-qsd8r
<Controller
as={ReactSelect}
options={[
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
]}
name="ReactSelect"
isClearable
control={control}
/>
推荐阅读
- android - 我可以将参数发送到 kotlin 中的接口吗?
- database - MongoDB 聚合和更新练习
- git - 如何处理git-flow中分支之间的依赖关系?
- testing - Google Play 封闭和内部测试轨道的问题
- javascript - 为什么我的四格拼块不会每秒都从画布上掉下来?
- c++ - C++写访问冲突
- flutter - 如何有能力同时使用 Navigator.push 和 Navigator.pushNamed 颤振
- html - HTML 无法识别 css 文件并且不会导入它
- python - 百分比增加,groupby,随着时间的推移(使用 Python)
- python - 从具有概率权重的列表中生成数字列表