reactjs - React 16 类型 'DetailedHTMLProps, HTMLDivElement>' 上不存在属性

标签 reactjs typescript

由于 React 16 现在允许 custom DOM attributes ,我试图在我的 Typescript 代码中利用它:

import * as React from 'react';

<div className="page" size="A4">
</div>

但收到此错误消息:

error TS2339: Property 'size' does not exist on type 'DetailedHTMLProps< HTMLAttributes< HTMLDivElement>, HTMLDivElement>'.

thread建议做一个module augmentation,所以我尝试了这种方式:

import * as React from 'react';

declare module 'react' {
     interface HTMLProps<T> {
        size?:string;
    }    
}

同样的错误信息。

最后,我还尝试将page声明为一个新的HTML标签:

declare global {
  namespace JSX {
    interface IntrinsicElements {
      page: any
    }
  }
}

<page className="page" size="A4">
</page>

它摆脱了错误消息,但是 size 属性在编译代码中被完全忽略,我最终得到:

<page className="page">
</page>

理想情况下,最后一个是我的首选解决方案。我想将 size 自定义属性与 page 自定义标签一起使用。

tsconfig.js

{
  "compilerOptions": {
    "outDir": "build/dist",
    "module": "esnext",
    "target": "es5",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "allowSyntheticDefaultImports": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "allowUnusedLabels": true,
    "allowUnreachableCode": true
  }
}

最佳答案

HTML 支持自定义属性的 data-* 属性类型。您可以阅读更多 here .

Definition and Usage The data-* attributes is used to store custom data private to the page or application.

The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.

The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

The data-* attributes consist of two parts:

  • The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-"
  • The attribute value can be any string

Note: Custom attributes prefixed with "data-" will be completely ignored by the user agent.

除了使用 size="A4",您还可以使用 data-size="A4"

示例

<div className="page" data-size="A4">
  // ....
</div>

关于reactjs - React 16 类型 'DetailedHTMLProps, HTMLDivElement>' 上不存在属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46215614/

相关文章:

javascript - Material-ui 表行 onClick 绕过复选框选择

javascript - 尝试使用 React 的 <select> 创建下拉选择菜单并将数组中的用户映射为选项

reactjs - fontFamily "$text-font-family"不是系统字体,没有通过 Font.loadAsync 加载

angular - 使用接口(interface)强制 typescript 中的类型

javascript - Angular settimeout 不工作 Javascript

javascript - 单引号和双引号追加

node.js - 如何使用 React Router 从 React.js 的子路径修复错误的代理重定向?

javascript - react 组件不呈现来自 redux 存储的新数据

javascript - 任意泛型的 typescript map

函数返回函数时的 TypeScript 类型推断问题