【问题标题】:How to properly parse sub-components in a Stencil.js component如何正确解析 Stencil.js 组件中的子组件
【发布时间】:2022-06-13 23:20:01
【问题描述】:

我正在尝试使用 Stencil.js 创建具有以下结构的选项卡组件:

<custom-tabs>
    <custom-tab active label="Label 1">
        Some generic HTML content <custom-rating value="4"></custom-rating>
    </custom-tab>
    <custom-tab active label="Label 2">
        Some more generic HTML content <custom-rating value="5"></custom-rating>
    </custom-tab>
</custom-tabs>

父组件需要通过解析每个 'custom-tab' 组件(没有 render 方法)并从每个选项卡中提取 'label' 参数来渲染底层 HTML,构建这些标签的导航列表和同样提取每个选项卡的主要内容并显示在选项卡的相应面板中。

在我的父组件中,我抓住了“componentWillLoad”挂钩中的选项卡

componentWillLoad() {
    // Grab tabs from this component
    this.tabs = Array.from(this.el.querySelectorAll('custom-tab'));
    console.log(this.tabs);
  }

然后在渲染函数中我尝试输出内容:

return (
      <div>
        {this.tabs.map((tab: HTMLCustomTabElement, index: number) => {
          return (
            <div
              role="tab"
              onClick={() => this.openTab(index)}>
              {tab.label} {tab.innerHTML}
            </div>
          );
        })}
      </div>
    );

问题是tab.innerHTML 没有解析custom-rating 组件,只是将其作为文本输出。您能否建议显示选项卡内容的正确方法,以便正确解析所有内容?

【问题讨论】:

    标签: javascript typescript web-component custom-component stenciljs


    【解决方案1】:

    你可以通过设置the innerHTML property来输出HTML:

    return (
      <div>
        {this.tabs.map((tab: HTMLCustomTabElement, index: number) => {
          return (
            <div
              role="tab"
              onClick={() => this.openTab(index)}>
              {tab.label}
              <div innerHTML={tab.innerHTML}></div>
            </div>
          );
        })}
      </div>
    );
    
    

    【讨论】:

    • 就是这样!根据需要工作。非常感谢!
    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 2019-05-28
    相关资源
    最近更新 更多