简体   繁体   English

带有 React Hook Form 的 Typescript 和 React-select 表单未提交的多个选定值

[英]Typescript with React Hook Form and React-select Multiple selected value not submitted by the form

I am using react hook form and react select with typescript.我正在使用反应挂钩形式并使用打字稿反应选择。 Its works fine for single selected value.它适用于单个选定值。 But when I choose isMulti for multiple selected value, I am unable to get the value from the submitted form.但是当我为多个选定值选择 isMulti 时,我无法从提交的表单中获取值。 Here is the code这是代码

 interface ITopic {
  value: string;
  label: string;
}

........... …………

const topicOptions : ITopic[] = [
    { value: 'javascript', label: 'JAVASCRIPT' },
    { value: 'php', label: 'PHP' },
    { value: 'python', label: 'PYTHON' },
    { value: 'java', label:'JAVA' },
    { value: 'C#', label: 'C#' }
]

type TopicType = { label: string, value: string }

const [selectedTopic, setSelectedTopic] = useState<readonly ITopic[]>([]);

.......... …………

<Controller
   control={control}
   render={({ field: { onChange, value, name, ref } }) =>{
   const handleSelectionChange = (topicOptions: readonly SelectOptionType[]) => {
   setSelectedTopic(topicOptions)
   console.log(selectedTopic)
  }
   return  (
      <Select
      isMulti
      name={name}
      value={selectedTopic}
      options={topicOptions} 
      onChange={handleSelectionChange}
      />
  )}}
  name="topics"
/>   

I am getting empty topics value.我得到空主题值。 Need Help.需要帮忙。 Thank you.谢谢你。

First, if you are using react-hook-form to manage your form, you shouldn't in addition have useState for your variable.首先,如果你使用react-hook-form来管理你的表单,你不应该另外为你的变量使用useState

What you want to do instead is to use onChange from the Controller 's render method.您要做的是使用Controllerrender方法中的onChange

For instance, my multi select code is (assuming topicOptions is an array of TopicType: { label:string; value:string } )例如,我的多选代码是(假设topicOptions是 TopicType 的数组TopicType: { label:string; value:string }

      <Controller
        control={control}
        name="topics"
        render={({ field: { onChange, value } }) => (
          <Select
            isMulti
            name="topics"
            options={topicOptions}
            value={topicOptions.filter((el) => value?.includes(el.value))}
            onChange={(option: TopicType[] | null) => {
              if (option === null) {
                onChange(null);

                return;
              }

              onChange(option.map((el) => el.value));
            }}
          />
        )}
      />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM