【问题标题】:StencilJS: Missing "h" import for JSX typesStencilJS:缺少 JSX 类型的“h”导入
【发布时间】:2020-08-02 03:23:45
【问题描述】:

我正在尝试使用模板创建 Web 组件,并且在 TSX 文件中使用 h1 标记时出现以下错误:

[ ERROR ]  Missing "h" import for JSX types: ./src/components/side-drawer/side-drawer.tsx:1:19
           In order to load accurate JSX types for components, the "h" function must be imported from "@stencil/core"
           by each component using JSX. For example: import { Component, h } from '@stencil/core';

下面是我的 web 组件的代码:

import { Component } from "@stencil/core";

@Component({
  tag: "vs-test",
})
export class Test {
  render() {
    return (
      <div>
        <h1>Hello</h1>
      </div>
    );
  }
}

【问题讨论】:

    标签: javascript jsx web-component stenciljs tsx


    【解决方案1】:

    好吧,终于从official docs得到它。

    自 stencil v1.0.0 以来发生了重大变化

    重大变化

    JSX 的一个常见问题是每个单独的项目都使用全局 JSX 类型。许多必需的更改是为了避免全局类型,这通常会导致从大量包导入的应用程序出现问题。另一个变化是让每个组件都导入其渲染器,例如 JSX 的 h() 函数。

    需要导入 { h } 为了在 Stencil 应用程序中渲染 JSX,必须从 @stencil/core 导入 h() 函数:

    import { h } from '@stencil/core';
    
    function app() {
      return <ion-app></ion-app>
    }
    

    h 代表“超脚本”,这是 JSX 元素转换成的内容(它是在运行时渲染时执行的实际函数)。 Stencil 的 h 导入等效于 React 的 React.createElement。这也解释了为什么应用程序的 tsconfig.json 设置了 { "jsxFactory": "h" } 配置,这在 TypeScript 的 JSX 工厂函数文档中有更详细的说明。

    【讨论】:

      【解决方案2】:

      您是否尝试将 h 依赖项添加到您的导入中?

      从'@stencil/core'导入{组件,h};

      【讨论】:

      • 但是为什么我们需要 h 导入,在 jsx 和 tsx 中大多数 html 标签都可以按原样工作?
      • 在编译时所有 jsx "return ()" 都被解析为 "return h()" 所以你需要那个依赖,基本上和 React 一样,你需要即使您不直接在代码中使用它,也可以从“react”导入 React
      猜你喜欢
      • 2017-03-07
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多