StencilJs/Jsx: 在嵌套组件中渲染 HTMLElements

StencilJs/Jsx: render HTMLElements in nested component

这是我的组件:

@Component({
  tag: "my-alert-list",
  styleUrl: "alert-list.scss",
  shadow: true,
})
export class AlertList {
  @State() alertList: object[] = [];

  @Method()
  async appendAlert(
    type: string,
    message: string,
    htmlContent: object,
    canClose: boolean = false,
    closeDelay: number
  ) {
    let alertBoxElement = (
      <my-alert-box
        alert-type={type}
        message={message}
        can-close={canClose}
        close-delay={closeDelay}
        opened
      >
      {htmlContent}
      </my-alert-box>
    );
    this.alertList = [
      ...this.alertList,
      alertBoxElement
    ]
  }


  render() {
    return (
      <Host>
        {this.alertList}
      </Host>
    );
  }
}

方法appendAlert 旨在将新的my-alert-box 元素附加到警报列表。 在同样的情况下,我不想将简单的文本传递给 my-alert-box 而是一些 HTML 块。 (my-alert-box 有一个接收器插槽元素,我验证它可以工作)。 如您所见,我尝试使用 htmlContent 变量来实现此目的,但如果我这样做,它当然不起作用:

$('#alertlist')[0].appendAlert(type='info',message='', htmlContent=document.createElement('div'))

我收到错误:

[STENCIL-DEV-MODE] vNode passed as children has unexpected type. Make sure it's using the correct h() function. Empty objects can also be the cause, look for JSX comments that became objects.

关于如何实现这一目标的任何想法?

这是不可能的,因为 JSX 的工作方式不同。您可以将 htmlContent 作为字符串传递并在 my-alert-box 上使用 innerHTML 但这很危险(XSS)。

Ionic 的 ion-alertmessage prop 具有相同的限制...参见 https://ionicframework.com/docs/api/alert#properties which has a link to https://ionicframework.com/docs/techniques/security,他们在那里解释了他们如何进行一些基本的 DOM 消毒(@ionic/core 也是用 Stencil 构建的。