reactjs - 无法将 className 或 style 等 Prop 传递给自定义组件的 Prop

标签 reactjs react-props react-functional-component

我正在努力创建一个 TypeScript 友好的 NPM 包,但我无法将常见的 HTML 属性作为 Prop (如 classNamestyle)传递给我的组件。我希望不必通过扩展具有所有所需 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 ,例如 classNamestyle.

我的 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/

相关文章:

javascript - react native 如何处理对象和数组?

reactjs - 如何从 react 中的子标签访问数据

javascript - 我们可以将 setState 作为 props 从一个组件传递到另一个组件,并在 React 中从子组件更改父状态吗?

reactjs - 如何在 React 函数组件中使用数组状态?

css - 'react-scripts' 构建在 CSS 中嵌入一些图像作为数据 uri

javascript - 带有 json 数据的 axios post 请求

javascript - jest.spyOn() 在 react 钩子(Hook)上调用时出现类型错误

javascript - 在 React JSX 中访问引号内的 Prop

reactjs - 对于带有反应查询的大型 react 应用程序,推荐的方法是什么?

javascript - 功能 react : Increment react state after if statement