我正在努力创建一个 TypeScript 友好的 NPM 包,但我无法将常见的 HTML 属性作为 Prop (如 className
和 style
)传递给我的组件。我希望不必通过扩展具有所有所需 Prop 的界面来手动将每个属性添加到我的 Prop 列表中。我的简化组件如下所示:
import React, { Key, ReactElement } from "react";
interface MyComponentProps extends React.HTMLAttributes<HTMLDivElement> {
customText: string;
uniqueKey?: Key;
}
export function MyComponent({uniqueKey, customText, ...props}: MyComponentProps): ReactElement {
return (
<div key={uniqueKey} {...props}>{customText}</div>
);
}
我创建了一个 uniqueKey
Prop ,因为它不能只命名为 key
(与 ref
相同)。我试图扩展 props
参数以将任意 Prop 传递给我的组件,但它似乎没有什么不同。我将这个组件导入到我的项目中并尝试像这样调用它:
<MyComponent customText="Hello World" uniqueKey={123} className="myClass" />
我收到错误:属性“className”在类型“MyComponentProps”上不存在。
我希望这会起作用,因为 MyComponentProps
扩展了 HTMLAttributes
,它具有我想要的 Prop ,例如 className
和 style
.
我的 index.d.ts
文件如下所示:
import React, { Key, ReactElement } from "react";
interface MyComponentProps extends React.HTMLAttributes<HTMLDivElement> {
customText: string;
uniqueKey?: Key;
}
export declare function MyComponent({ uniqueKey, customText, ...props }: MyComponentProps): ReactElement;
export {};
最佳答案
获取特定 HTML 元素可用属性的最简单方法是使用 JSX.IntrinsicElements
。
type MyComponentProps = JSX.IntrinsicElements['div'] & {
customText: string;
uniqueKey?: Key;
}
在幕后,JSX.IntrinsicElements['div']
是以下类型。
React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
关于reactjs - 无法将 className 或 style 等 Prop 传递给自定义组件的 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65457886/