带样式组件的 onClick 的打字稿问题

Typescript issue with onClick with styled-components

我正在使用自定义 Icon 组件,如下所示:

<Icon onClick={() => {}} />

但是,TypeScriptIcon 下划线并给出了以下消息,我不太明白:

Property 'onClick' does not exist on type 'IntrinsicAttributes & Pick<Pick<Props, "className" | "name"> & Partial<Pick<Props, never>>, "className" | "name"> & { theme?: any; } & { as?: "symbol" | "object" | ... 174 more ... | undefined; }'.ts(2322)

我的 Icon 组件是一个 styled-component,如下所示:

interface Props {
  name: string
  className?: string
}

const Icon = styled(({name, className, ...props}: Props) => <i className={`material-icons ${className}`} {...props}>{name}</i>)``

我能够通过将以下内容添加到 Icon 的接口声明以允许任何 属性:

来使 TypeScript 静音
[x: string]: any

但感觉像是hack,我想了解问题并找到合适的解决方案。

有趣的是,如果我以相同的方式使用自定义 Button 组件,我不会收到错误消息:

<Button onClick={() => {}} />

const Button = styled.button``

您对 Icon 的属性定义告诉 typescript,只有 nameclassName 是有效属性。

interface Props {
  name: string
  className?: string
}

如果你还想允许 onClick 你必须添加它:

interface Props {
  name: string;
  className?: string;
  onClick: (e: Event) => void;
}

或者如果您想要允许所有对 <i> 有效的属性,您可以使用以下内容:

interface Props extends React.HTMLAttributes<HTMLElement> {
  name: string
}