【问题标题】:stenciljs conditional render return in tsxtsx 中的 stenciljs 条件渲染返回
【发布时间】:2019-02-18 10:09:31
【问题描述】:

我的 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 jsx tsx stenciljs


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我没想过要尝试使用没有大括号的变量。您可能已经猜到了,我是 JSX 新手。现在,如果我能弄清楚为什么我的 TSX 文件显示关于未使用标签的警告。 [ts] 'Tag' 已声明,但其值从未被读取。
    • 请注意,使用大写字母“T”声明标签很重要。如果您改为使用小写“t”声明“const tag = ...”,那么您将收到警告并且该项目将不会呈现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 2019-04-15
    • 2020-11-14
    相关资源
    最近更新 更多