【问题标题】:Using web components in react with only a CDN使用 Web 组件仅与 CDN 发生反应
【发布时间】:2021-03-14 03:56:41
【问题描述】:

我有一个客户,他有一个完整的 UI 元素库,他们希望我们使用。他们将这些 javascript 和 css 文件托管在 CDN 上。我无权访问源代码。我唯一拥有的是我的 index.html 文件的一组脚本标签。

<script type="module" crossorigin="anonymous" cross src="https://design.customerName.no/assets/DesignSystemName.esm.min.js"></script>
<script nomodule src="https://design.customerName.no/assets/DesignSystemName.es5.min.js"></script>

<script type="module" crossorigin="anonymous" src="https://design.customerName.no/assets/DesignSystemName-webcomponents/DesignSystemName-webcomponents.esm.js"></script>
<script nomodule src="https://design.customerName.no/assets/DesignSystemName-webcomponents/DesignSystemName-webcomponents.js"></script>

现在我想在我的反应代码中使用这个库中的某些 WebComponents。到目前为止,我能够使用它们的唯一方法是将纯 html 编写为字符串并将该 html 注入到反应组件中。像这样

import React from 'react';
    
const body = `
  <webcomponent-tab-panel titles="title1, title2">
    <span slot="title1">
      <h2 class="align-center">title2</h2>
    </span>

    <span slot="title2">
      <h2 class="align-center">title2</h2>
    </span>
  </webcomponent-tab-panel>
`

const Steps = () => {
  return (
    <div dangerouslySetInnerHTML={{__html: body}} />
  )
}

export default Steps;

它现在有效,但我觉得应该有更好的方法来做到这一点。有没有人有使用这种 CDN 中的 Web 组件的经验?

【问题讨论】:

    标签: javascript html reactjs typescript web-component


    【解决方案1】:

    React.createElement 将允许您在 JSX 中编写自定义元素,例如 。由于 react 会将小写标签视为不是 react 组件而是 html。

    【讨论】:

      【解决方案2】:

      我找到了解决方法。我正在使用 TypeScript。所以当我尝试在 JSX 中使用 webcomponents 时,它不会在 JSX.intrinsicelements 类型上找到它。我创建了一个 types.d.ts 文件,在其中将 webcomponents 添加到 JSX 命名空间。

      像这样

      declare namespace JSX{
        interface IntrinsicElements{
          "WebComponent-Name": React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement>
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-27
        • 2021-08-22
        • 2020-03-19
        • 2019-10-16
        • 2018-10-24
        • 2016-12-18
        • 2022-07-08
        • 2021-08-10
        相关资源
        最近更新 更多