从反应选择和打字稿中选择组件

时间:2020-11-03 16:40:51

标签: reactjs typescript react-select

我正在尝试使用带有组件脚本的react-component中的Select组件,但出现一些重载错误。在我的代码段下方:

type SelectedProps = {
  name: string;
  label: string;
  placeholder: string;
  readOnly: boolean;
  options: {
    label: string;
    value: string
  }
}

export function SelectFormik({ label, options, ...rest }: SelectedProps): ReactElement<any> {
  const [field, meta, helpers] = useField(rest) // <-- Had set some type here I guess

  const handleChange = (selected: SelectedProps["options"], action) => {
    helpers.setValue(selected)
  }


  return (
    <Box mb="2">
      <FormControl>
        { label && <FormLabel htmlFor={rest.name}>{label}</FormLabel>}
        <Select
          {...rest}
          {...field}
          options={options}
          onChange={handleChange}
          styles={selectStyles}
          isClearable
          isSearchable
        />

        <FormErrorMessage isInvalid={!!meta.error}>{meta.error}</FormErrorMessage>
      </FormControl>
    </Box>
  )
}

和我得到的错误:

(alias) class Select<OptionType extends OptionTypeBase = { label: string; value: string; }, T extends SelectBase<OptionType> = SelectBase<OptionType>>
import Select
No overload matches this call.
  Overload 2 of 2, '(props: Pick<Props<{ label: string; value: string; }>, ReactText> & import("/Users/marcos/Desktop/fitup-next/node_modules/@types/react-select/src/stateManager").Props<{ ...; }> & import("/Users/marcos/Desktop/fitup-next/node_modules/@types/react-select/src/Select").Props<...>, context?: any): StateManager<...>', gave the following error.
    Type '{ label: string; value: string; }' is not assignable to type 'OptionsType<{ label: string; value: string; }> | GroupedOptionsType<{ label: string; value: string; }> | undefined'.
      Type '{ label: string; value: string; }' is not assignable to type 'GroupedOptionsType<{ label: string; value: string; }>'.
  Overload 2 of 2, '(props: Pick<Props<{ label: string; value: string; }>, ReactText> & import("/Users/marcos/Desktop/fitup-next/node_modules/@types/react-select/src/stateManager").Props<{ ...; }> & import("/Users/marcos/Desktop/fitup-next/node_modules/@types/react-select/src/Select").Props<...>, context?: any): StateManager<...>', gave the following error.
...

我阅读了该错误,但我不明白,如果您能帮助我,我将不胜感激。谢谢各位抱歉,jr开发人员是jkk开发人员,kkkk。

1 个答案:

答案 0 :(得分:0)

您的接口SelectedPropsoptions定义为单个选项对象,当您打算将其作为选项对象数组时。这就是您所发布的特定错误的来源。

type SelectedProps = {
  name: string;
  label: string;
  placeholder: string;
  readOnly: boolean;
  options: {
    label: string;
    value: string;
  }[];
}

似乎传递给value回调的onChange的类型是any,所以我不确定value的实际含义。也许在useField上设置通用名称会有所帮助。

相关问题