如何让TypeScript引擎在JSX中允许自定义HTML属性?

7

我猜测Visual Studio Code中的TypeScript引擎已经更新,现在第一次发现我预先存在的HTML元素上的自定义属性是无效的。这是一个使用Babel/React/JSX的项目,没有任何TypeScript。

<div custom="bar" />

注意:它们(从技术上讲)是无效的,但我使用它们,所以我知道自己在做什么(这是故意的)。

在CodePen上查看!

另请参阅


你可以使用 data- 属性,例如 data-custom,这是有效的。 - meda
请提供错误信息。 - Pavel
3个回答

11

React类型定义文件(默认情况下,使用create-react-app时为index.d.ts)包含所有标准HTML元素的列表,以及已知属性。

为了允许自定义HTML属性,您需要定义其类型。 通过扩展HTMLAttributes接口来实现:

import { HTMLAttributes } from "react";

declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    // extends React's HTMLAttributes
    custom?: string;
  }
}

在 TypeScript 文档中了解更多关于模块增强的内容。


3
这会破坏对于 'react' 模块的 TypeScript 类型检查。 - Omar Abid
1
不要忘记导入 HTMLAttributes - kjetilh

9

5
添加细节到答案。 - janith1024
1
欢迎来到 Stack Overflow!请不要仅仅把你的源代码扔在这里。友好地尝试给出一个良好的描述,以便其他人会喜欢并点赞它。参见:如何撰写一个好的答案? - sɐunıɔןɐqɐp
答案竟然是连字符……一直都是吗?真正的英雄并不总是穿斗篷! :) - undefined

2

项目结构:

☁  extends-react-types  tree -I 'node_modules' 
.
├── App.tsx
├── index.d.ts
├── package-lock.json
├── package.json
└── tsconfig.json

0 directories, 5 files

软件包版本:

{
  "name": "extends-react-types",
  "devDependencies": {
    "@types/react": "^16.9.56",
    "typescript": "^4.3.5"
  },
  "dependencies": {
    "react": "^16.8.6"
  }
}

tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "lib": [
            "dom"
        ],
        "allowSyntheticDefaultImports": true,
        "moduleResolution": "Node",
        "jsx": "preserve",
    }
}

App.tsx:

import React from 'react';

interface HomeProps extends React.ComponentPropsWithRef<'div'> {}
export default function Home(props: HomeProps) {
  return (
    <div>
      <p _name="name" _error={true}>
        123
      </p>
    </div>
  );
}

您可以看到,p 元素中有两个自定义 HTML 属性:_name_error。现在,我们需要扩展 ReactHTMLAttributes 接口,以包含这两个自定义 HTML 属性。

选项 1:

index.d.ts

import 'react';

declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    _name?: string;
    _error?: boolean;
  }
}

输出:

在此输入图片描述

选项2:

declare namespace React {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    _name?: string;
    _error?: boolean;
  }
}

输出:

输入图像描述


(注:该段文字为格式说明,无需翻译)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接