【问题标题】:Can't pass props like className or style to custom component's props无法将 className 或 style 等道具传递给自定义组件的道具
【发布时间】:2021-04-04 01:27:06
【问题描述】:

我正在创建一个对 TypeScript 友好的 NPM 包,但我无法将常见的 HTML 属性作为 classNamestyle 等道具传递给我的组件。我希望不必通过扩展具有所有所需道具的界面来手动将每个属性添加到我的道具列表中。我的简化组件如下所示:

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 属性,因为它不能只命名为key(与ref 相同)。我尝试扩展 props 参数以将任意道具传递给我的组件,但它似乎没有任何区别。我将此组件导入我的项目并尝试将其称为:

<MyComponent customText="Hello World" uniqueKey={123} className="myClass" />

我收到错误:Property 'className' does not exist on type 'MyComponentProps'.

我希望这会起作用,因为MyComponentProps 扩展了HTMLAttributes,它具有我想要的道具,例如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 {};

【问题讨论】:

    标签: reactjs react-props react-functional-component


    【解决方案1】:

    获取特定 HTML 元素的可用道具的最简单方法是使用 JSX.IntrinsicElements

    type MyComponentProps = JSX.IntrinsicElements['div'] & {
        customText: string;
        uniqueKey?: Key;
    }
    

    在底层,JSX.IntrinsicElements['div'] 是以下类型。

    React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
    

    【讨论】:

    • 谢谢。这似乎确实可以解决问题!你能帮我理解为什么扩展React.HTMLAttributes&lt;HTMLAnchorElement&gt; 对我也不起作用吗?您的解决方案还显示,我可以消除我的 uniqueKey 道具,并且在创建 MyComponent 的实例时也只使用 key
    • HTMLAnchorElement 不正确,因为您将道具传递给 div 元素。如果你用HTMLDivElement 替换它,它应该可以工作,尽管它会丢失key 属性。
    • 糟糕,抱歉——我的原始示例中有错字。在我的真实代码中,我使用了一个锚元素,但在我上面的示例中,它是一个 div。我修正了我原来问题中的错字。话虽如此...为什么在我给定的示例中扩展React.HTMLAttributes&lt;HTMLDivElement&gt; 不起作用?即使听起来你建议它应该工作 - 不幸的是它没有。这是一个 NPM 包,在测试我的包时,我可以使用 className 之类的属性,但不能在将我的 NPM 包作为依赖项的项目中使用。
    • @types/react 是否安装在您正在使用您的包的项目中?
    • 是的,版本 17.0.0
    猜你喜欢
    • 2021-09-11
    • 2020-12-22
    • 2020-12-21
    • 2018-04-08
    • 1970-01-01
    • 2021-11-10
    • 2019-06-30
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多