我正在使用一个使用React和Typescript的项目,但是我想开始在项目中使用本机Web组件来逐步淘汰某些React组件。
当我尝试在我的person-info某些JSX中包含使用组件时,出现此错误。
person-info
Property does not exist on type 'JSX.IntrinsicElements'
我已经看过其他一些与这些问题有关的问题,但它们似乎都与本地Web组件无关。
在项目中使用Web组件时,如何使Typescript和React正常播放?
PersonInfo.mjs
const css = ` <style> :host([hidden]) { display: none; } :host { align-items: center; display: grid; font-weight: normal; grid-gap: var(--spacing-size-a) var(--spacing-size-a); grid-template-areas: 'picture heading' 'picture sub-heading'; grid-template-columns: auto 1fr; justify-items: start; } div { grid-area: picture; } h1, h2 { margin: 0; padding: 0; } h1 { align-self: end; font-size: var(--l-text-size); font-weight: normal; grid-area: heading; text-transform: capitalize; } h2 { align-self: start; font-size: var(--m-text-size); grid-area: sub-heading; } ion-icon { font-size: 56px; } </style> ` const html = ` <div> <ion-icon name="md-contact"></ion-icon> </div> <h1>Heading</h1> <h2>Sub-heading</h2> ` class PersonInfo extends HTMLElement { static get observedAttributes () { return [ 'heading', 'subHeading', 'size' ] } constructor () { super() this.attachShadow({mode: 'open'}) this.shadowRoot.appendChild(template.content.cloneNode(true)) } connectedCallback () { this.shadowRoot.querySelector('h1').innerText = this.getAttribute('heading') this.shadowRoot.querySelector('h2').innerText = this.getAttribute('subHeading') } get heading () { return this.getAttribute('heading') } set heading (newValue) { this.setAttribute('heading', newValue) this.shadowRoot.querySelector('h1').innerText = newValue } get subHeading () { return this.getAttribute('subHeading') } set subHeading (newValue) { this.setAttribute('subHeading', newValue) this.shadowRoot.querySelector('h2').innerText = newValue } get size () { return this.getAttribute('size') } set size (newValue) { this.setAttribute('size', newValue) } } const template = document.createElement('template') template.innerHTML = `${css}${html}` window.customElements.define('person-info', PersonInfo)
进口声明
import '../../common/WebComponents/PersonInfo.mjs'
JSX中的用法
<main> <person-info heading='Bruce Wayne' subHeading="I'M BATMAN!" /> </main>
我在这里弄清楚了如何解决这个特定的错误。
import * as React from 'react' declare global { namespace JSX { interface IntrinsicElements { 'person-info': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>; } } }
但是,此后我又遇到了另一个错误,这是由于我在组件上使用了自定义属性。多亏Shanon的评论,我也想出了解决方法,最后得到了我刚刚导入App.tsx文件中的最终代码。
App.tsx
import * as React from 'react' declare global { namespace JSX { interface IntrinsicElements { 'person-info': PersonInfoProps } } } interface PersonInfoProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> { heading: string, subHeading: string, size?: string }