簡體   English   中英

如何將 React-Select 中的選定值轉發到 react-hook-form

[英]How to forwardRef selected value from React-Select to 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}
/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM