首页 > 解决方案 > 如何将 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;

代码沙盒中的完整代码。谁能帮我?

标签: reactjsreact-hook-form

解决方案


你考虑过使用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}
/>

推荐阅读