【问题标题】:How can I combine a React element and text inside a ternary?如何在三元组中组合 React 元素和文本?
【发布时间】:2018-06-16 09:28:36
【问题描述】:

通常如果你有类似的东西:

<SomeComponent foo={bar} />

您可以使用三元组使其成为可选:

{bar ? <SomeComponent foo={bar} /> : null}

但是如果你开始的块包含一个组件加上一些文本(一个空格)和一个变量,例如:

<SomeComponent foo={bar} /> {foobar}

用括号括起来是行不通的:

{bar ? (<SomeComponent foo={bar} /> {foobar}) : null}

事实上,我发现让它工作的唯一方法是将所有内容包装在另一个元素中:

{bar ? <span><SomeComponent foo={bar} /> {foobar}</span> : null}

还有其他方法可以告诉 React:

<SomeComponent foo={bar} /> {foobar}

是一个离散的块,所以我可以在三元中使用它(在 JS 内部,而不是 JSX,逻辑)......而不添加无意义的包装器元素?

【问题讨论】:

    标签: reactjs jsx ternary


    【解决方案1】:

    您可以定义一个小组件来充当包装器,但不会呈现任何标记,但从技术上讲,它仍然是一个包装器。我通过定义Aux 组件来使用这种方法:

    const Aux = (props) => (props.children);
    

    那么你可以这样做:

    {bar ? <Aux><SomeComponent foo={bar} /> {foobar}</Aux> : null}
    

    这至少避免了生成的 html 中不必要的标记,这对于样式目的可能至关重要,例如,如果您使用的是 flex-box

    【讨论】:

      【解决方案2】:

      曾经有两种次优方法可以实现这一目标:

      1. 使用数组,这需要向 React 元素添加键:

        {bar ? [<SomeComponent key="1" foo={bar} />, " ", foobar] : null}
        
      2. 创建一个wrapper component,就像@margaretkru 建议的那样。

      但是对于 React 16.2.0+,你可以使用 improved fragments:

      {bar ? <React.Fragment><SomeComponent foo={bar} /> {foobar}</React.Fragment> : null}
      

      或者,更好的是,您可以使用简写语法:

      {bar ? <><SomeComponent foo={bar} /> {foobar}</> : null}
      

      片段不会产生额外的容器元素。

      【讨论】:

      • 哇,太酷了。我以为你只能在从render返回时使用片段,但现在我想起来应该没关系,反正都是jsx :)
      • 技术上&lt;&gt; 仍然是一个包装器,但是因为我怀疑不存在真正的无包装器解决方案(并且因为它不是真正的“无意义”,因为它正在定义一个片段),这似乎是最好的可行选择......而且,就像@margaretkru 所说,这很酷:)
      • 是的,它在语义上是一个包装器,但不会作为一个包装器呈现。我为较旧的 React 版本更新了答案。 @margaretkru 我链接到您非常优雅的解决方案。 :)
      猜你喜欢
      • 2016-12-19
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多