【问题标题】:Adding a custom property to an HTML attribute in react with typescript将自定义属性添加到 HTML 属性以与打字稿反应
【发布时间】:2020-08-12 10:58:13
【问题描述】:

有没有办法为 react HTML 元素添加自定义类型?我将 React 16.13.1 与 Create React App 和 Typescript 3.9.5 一起使用。我找到的唯一解决方案是禁用类型检查,这并不理想,或者在每个组件的顶部声明 react 模块接口(如下所示)。有没有办法在全球范围内添加它?还是其他解决方案?

declare module 'react' {
    interface HTMLAttributes<T> {
        customAttribute?: any;
        // more attributes...
    }
}

我尝试将它添加到创建的 index.d.ts 文件并添加到 tsconfig.json "compilerOptions": {"types":["./index.d.ts"]} 但我仍然得到

TS2322: Type '{ children: Element[]; customAttribute: string; className: string; }' is not assignable to type 'DetailedHTMLProps&lt;HTMLAttributes&lt;HTMLDivElement&gt;, HTMLDivElement&gt;'.   Property 'customAttribute' does not exist on type

感谢您的帮助。

【问题讨论】:

  • 您是否尝试使用声明文件?在你的项目中添加一个index.d.ts,类型应该是全局可用的
  • 是的。当我说我创建了一个 index.d.ts 文件但我仍然收到 TS2322 错误时,这就是我正在尝试的。
  • 查看了有关声明的文档后,我意识到我错误地导出和导入了我的声明。感谢您的评论,确认声明是正确的前进方式。

标签: reactjs typescript


【解决方案1】:

添加index.d.ts文件并在组件中导入接口解决了这个问题。

// index.d.ts
import "react";

declare module 'react' {
    export interface HTMLAttributes<T> {
        customAttribute?: any;
    }
}

将其添加到任何使用打字的组件中:

// component
import HTMLAttributes from "../index.d";

function MyComponent() {
   return <div customAttribute=""></div>
}

或将 index.d.ts 添加到 tsconfig

//tsconfig.json
"include": [ "path/to/index.d.ts" ]

【讨论】:

  • 它不适用于第二种方式,我将 "include": [ "path/to/index.d.ts" ] 添加到我的 tsconfig.json 文件中,但它仍然得到同样的错误
【解决方案2】:

如果您希望默认包含所有类型声明,您可以使用typeRoots 编译器选项。

您只需将以下内容添加到您的 TS 配置文件中:

  "compilerOptions": {
    "typeRoots": [
      "./node_modules/@types/",
      "./"
    ]
  }
}```

References:
1. [Create global.d.ts][1]
2. [Typescript typeRoots][2]


  [1]: https://stackoverflow.com/questions/57125019/create-react-app-typescript-global-d-ts-file-doesnt-work
  [2]: https://www.typescriptlang.org/tsconfig#typeRoots

【讨论】:

    猜你喜欢
    • 2018-06-13
    • 2023-01-16
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2019-05-23
    • 2015-06-24
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多