reactjs – 使用React 16在“DetailedHTMLProps,HTMLDivElement>”类型中不存在属性

前端之家收集整理的这篇文章主要介绍了reactjs – 使用React 16在“DetailedHTMLProps,HTMLDivElement>”类型中不存在属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
由于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建议进行模块扩充,所以我尝试了这种方式:

import * as React from 'react';

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

相同的错误消息.

最后,我还尝试将页面声明为新的HTML标记

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

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

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

<page className="page">
</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>
原文链接:https://www.f2er.com/react/300832.html

猜你在找的React相关文章