tsx 中的 stenciljs 条件渲染 return

stenciljs conditional render return in tsx

我的 stenciljs 渲染函数目前是这样用 typescript 编写的:

render() {
  if( this._isInline ) {
    return (
      <span>
        <slot />
      </span>
    );
  } else {
    return (
      <div>
        <slot />
      </div>
    );
  }
}

但我更喜欢这样写:

render() {
  const tag = this._isInline ? 'span' : 'div';
  return (
    <{tag}>
      <slot />
    </{tag}>
  );
}

但这给了我一堆错误信息。

有没有办法编写 jsx 代码,以便我有条件打开和关闭标记?

您可以使用以下代码实现:

render() {
   const Tag = this._isInline ? 'span' : 'div';
   return (
     <Tag>
       <slot />
     </Tag>
   );
}