繁体   English   中英

使用React根据多种条件渲染HTML代码

[英]Render HTML code based on multiple conditions using React

我有几个要使用Array#map方法渲染的项目,以对其进行迭代并返回所需的元素。 但是,在某些情况下会构建HTML。

这是代码:

<span className="items-overview">
    {
    this.props.obj.items.map((item, index) => {

        return (
            (item.LeftParenthesis ? "<b>" + item.LeftParenthesis + "</b>" : "")
            + "<i>" + item.Description + "</i>"
            + (item.RightParenthesis ? "<b>" + item.RightParenthesis + "</b>" : "")
            + (item.LogicOperand && index < this.props.obj.Conditions.length - 1 ? "&nbsp;<span>" + item.LogicOperand + "</span>" : "") + "&nbsp;"                                 
        )            
    })
    }
</span>

结果如下(假设只有一项):

在此处输入图片说明

我尝试过的方法

  1. 我知道我可以有多个IF语句或switch语句来确定要返回的内容,但这有点混乱。 我宁愿避免这种情况
  2. 我真的不想使用危险的内部设置

有任何解决方法吗?

不要使用字符串:

return (
  <span>
    {
      item.LeftParenthesis &&
        <b>{item.LeftParenthesis}</b>
    }
    <i>{item.Description}</i>
    {
      item.RightParenthesis &&
        <b>{item.RightParenthesis}</b>
    }
    {
      item.LogicOperand && index < this.props.obj.Conditions.length - 1 &&
        <span>&nbsp;{item.LogicOperand}</span>           
    }
    &nbsp;          
  </span>
) 

这将为您的HTML层次结构添加更多span ,以便React可以正确呈现所有内容。 这使用React的条件渲染来根据条件渲染元素。

这不是解决方法,这是有条件呈现元素的正确方法。

为什么不使用实际的React组件而不是字符串?

您可以使用仅在条件为true时才会呈现的组件https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-with-logical--operator

<span className="items-overview">
    {this.props.obj.items.map((item, index) => {
        return (
            <span>
                {item.LeftParenthesis && <b>{item.LeftParenthesis}</b>}
                <i>{item.Description}</i>
                {item.RightParenthesis && <b>{item.RightParenthesis}</b>}
                {item.LogicOperand && index < this.props.obj.Conditions.length - 1 && (&nbsp;<span>{item.LogicOperand}</span>)}
                &nbsp;
            </span>                                       
        );
    )}
</span>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM