在react和Typescript中使用Web组件

问题描述 投票:0回答:1

我正在使用custom-elements中的Preact aka Web组件。问题是Typescript抱怨JSX.IntrinsicElements中没有定义元素-在这种情况下,是check-box元素:

<div className={styles.option}>
    <check-box checked={this.prefersDarkTheme} ref={this.svgOptions.darkTheme}/>
    <p>Dark theme</p>
</div>

错误信息(路径省略):

ERROR in MyComponent.tsx
[tsl] ERROR in MyComponent.tsx(50,29)
      TS2339: Property 'check-box' does not exist on type 'JSX.IntrinsicElements'.

很不幸,我遇到了以下可能无法解决的问题:

  1. https://stackoverflow.com/a/57449556/7664765 -这不是一个真正解决问题的答案,但涵盖了我的问题

我尝试将以下内容添加到我的typings.d.ts文件中:

import * as Preact from 'preact';

declare global {
    namespace JSX {
        interface IntrinsicElements {
            'check-box': any; // The 'any' just for testing purposes
        }
    }
}

我的IDE将导入部分和IntrinsicElements设为灰色,这表示它没有被使用(?!),而且还是无法正常工作。我仍然收到相同的错误消息。

  1. https://stackoverflow.com/a/55424778/7664765 -另外,为了做出反应,我尝试将其“转换”为预先执行的结果,结果与1相同。

我什至在file项目中找到了由Google维护的squoosh,他们在其中进行了以下操作以“填充”支持:

在与组件相同的文件夹中,包含以下内容的missing-types.d.ts文件,基本上具有与我相同的设置,但是具有index.ts文件而不是check-bock.ts,并且它们使用的是TS的较旧版本v3.5.3

declare namespace JSX {
  interface IntrinsicElements {
    'range-input': HTMLAttributes;
  }
}

我假设他们的构建没有失败,所以它如何工作以及如何正确定义自定义元素以在preact / react组件中使用它们?

我当前正在使用[email protected][email protected]

javascript reactjs typescript web-component custom-element
1个回答
0
投票

好,我设法使用module augmentation解决了它:

declare module 'preact/src/jsx' {
    namespace JSXInternal {

        // We're extending the IntrinsicElements interface which holds a kv-list of
        // available html-tags.
        interface IntrinsicElements {
            'check-box': unknown;
        }
    }
}

使用HTMLAttributes接口,我们可以告诉JSX哪些属性可用于我们的自定义元素:

// Your .ts file, e.g. index.ts
declare module 'preact/src/jsx' {
    namespace JSXInternal {
        import HTMLAttributes = JSXInternal.HTMLAttributes;

        interface IntrinsicElements {
            'check-box': HTMLAttributes<CheckBoxElement>;
        }
    }
}

// This interface describes our custom element, holding all its
// available attributes. This should be placed within a .d.ts file.
declare interface CheckBoxElement extends HTMLElement {
    checked: boolean;
}
© www.soinside.com 2019 - 2024. All rights reserved.