从react Select和typescript中选择组件



我试图使用typescript从react组件中选择组件,但我遇到了一些重载错误。下面是我的代码片段:

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开发者是jr开发者,kkkk。

您的接口SelectedPropsoptions定义为单个选项对象,而您希望它是一个选项对象数组。这就是你发布的特定错误的来源。

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

传递到onChange回调的value的类型似乎也是any,所以我不确定value到底是什么。也许在useField上设置泛型会有助于改进这一点。

最新更新