由于 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/