简体   繁体   English

使用 TypeScript 反应通用道具

[英]React Generic Props using TypeScript

I have a trouble using JSX generic props.我在使用 JSX 通用道具时遇到了麻烦。

I have the component Dropdown.tsx:我有组件 Dropdown.tsx:

export type DropdownValue = string | number | boolean | Array<unknown>;

export interface DropdownRecord<T extends DropdownValue> {
    label: string;
    value: T;
}

interface DropdownProps<T extends DropdownValue> {
    options: Array<DropdownRecord<T>>;
    initialValue?: T;
    onChange: (value: T) => void;
    minWidth?: number;
}

const Dropdown = <T extends DropdownValue>(props: DropdownProps<T>) => {
    return null;
}
const showByOptions = [
    { label: 'Show by 15', value: 15 },
    { label: 'Show by 30', value: 30 },
];

const [showBy, setShowBy] = useState(15);

<Dropdown options={showByOptions} onChange={setShowBy} />

But while using this component generic seems to not working properly.但是在使用这个组件时,泛型似乎无法正常工作。 I gave the error:我给出了错误:

Type 'Dispatch<SetStateAction<number>>' is not assignable to type '(value: DropdownValue) => void'.
  Types of parameters 'value' and 'value' are incompatible.
    Type 'DropdownValue' is not assignable to type 'SetStateAction<number>'.
      Type 'string' is not assignable to type 'SetStateAction<number>'.ts(2322)
index.tsx(25, 5): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & DropdownProps<DropdownValue>'
(JSX attribute) DropdownProps<DropdownValue>.onChange: (value: DropdownValue) => void

Why the value coming from onChange has type DropdownValue, not number?为什么来自 onChange 的值的类型是 DropdownValue,而不是数字? What am I doing wrong?我究竟做错了什么?

VSCode v1.62.2 React v16.4.0 TypeScript v4.2.3 VSCode v1.62.2 反应 v16.4.0 TypeScript v4.2.3

Thanks!谢谢!

React.memo overrides type of wrapped component, so if you use this you also need to export your component like this: React.memo 覆盖了包装组件的类型,所以如果你使用它,你还需要像这样导出你的组件:

export memo(Dropdown) as typeof Dropdown

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

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