reactjs 如何在React-Select中输入onChange

sqougxex  于 2023-04-05  发布在  React
关注(0)|答案(1)|浏览(165)

我需要帮助
如何输入依赖于isMulti的onChange。如何写出正确的依赖条件?

onChange?(
  option: SelectProps<T>.isMulti extends true ? MultiValue<T> : SingleValue<T>,
): void
export interface SelectProps<T> {
    options?: T[]
    value: T | T[] | null | undefined
    isDisabled?: boolean
    placeholder?: string
    titleByKey?: string
    isSearchable?: boolean
    isClearable?: boolean
    isCreatable?: boolean
    isMulti?: boolean
    filterByLabel?: boolean
    name?: string
    inputValue?: string
    onCloseResetsInput?: boolean
    onBlurResetsInput?: boolean
    formatCreateLabel?: (inputValue: string) => string
    onBlur?: FocusEventHandler
    getOptionLabel?(option: T): string | number | null | undefined
    getOptionValue?(option: T): string | number | boolean | null | undefined
    onChange?(
        option: SelectProps<T>.isMulti extends true ? MultiValue<T> : SingleValue<T>,
    ): void
    onInputChange?(newValue: string, actionMeta: InputActionMeta): void
    onInputKeyDown?(e: KeyboardEvent<HTMLElement>): void
    hasError?: boolean
    menuIsOpen?: boolean
    maxMenuHeight?: number
    menuPlacement?: string
    hideSelectedOptions?: boolean
    isLoading?: boolean
}

我不知道如何做到这一点)我怎么能键入onChange依赖于isMulti.如何写正确的依赖条件?

4uqofj5v

4uqofj5v1#

您可以为SelectProps接口创建一个泛型类型,该泛型类型扩展isMulti属性以定义传递给onChange方法的值的类型。以下是如何修改SelectProps接口和onChange定义:

type MultiValue<T> = T[];
type SingleValue<T> = T | null | undefined;

export interface SelectProps<T, Multi extends boolean> {
    // ... other properties
    isMulti?: Multi
    onChange?: (
        option: Multi extends true ? MultiValue<T> : SingleValue<T>,
    ) => void
    // ... other properties
}

现在,当你使用SelectProps接口时,你需要同时提供T和Multi类型,这将决定传递给onChange方法的值的类型:

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

const MyMultiSelect: React.FC<SelectProps<MyOption, true>> = (props) => {
    // ...
};

const MySingleSelect: React.FC<SelectProps<MyOption, false>> = (props) => {
    // ...
};

通过将第二个类型参数设置为true或false,您将根据select组件是多选还是单选来获得onChange方法的正确类型。

相关问题