![](/img/trans.png)
[英]How do you render or not render table data based on conditions, using a loop in React JS?
[英]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 ? " <span>" + item.LogicOperand + "</span>" : "") + " "
)
})
}
</span>
结果如下(假设只有一项):
我尝试过的方法
有任何解决方法吗?
不要使用字符串:
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> {item.LogicOperand}</span>
}
</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 && ( <span>{item.LogicOperand}</span>)}
</span>
);
)}
</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.