2017-08-03 78 views
0

我有几个项目需要使用Array#map method来遍历它们并返回所需的元素。但是,在某些情况下将构建HTML。使用React渲染基于多个条件的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> 

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

enter image description here

途径我已经试过

  1. 我知道我可以有多个IF语句或一个switch语句来确定返回的内容,但这会有点混乱。我宁愿避免这种
  2. 我真的不希望使用dangerously-set-inner

任何解决方法吗?

回答

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> 
) 

这将增加一些更span s到你的HTML使React可以正确渲染所有内容。这使用React's conditional rendering根据条件呈现元素。

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

+0

这工作就像一个魅力!由于span元素,我只需要安排一些CSS规则。谢谢你,先生! – ggderas

+0

@ggderas没问题,很高兴帮助! – Li357

0

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

您可以使用只会渲染组件,如果条件为真 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> 
+0

这仍然是无效的语法。 – Li357