[英]How do you do an if else statement in JSX/ES6 shorthand?
My data looks like this 我的数据看起来像这样
{
foo1: { name: 'Sara', rep: 'John' },
foo2: { name: 'Bob'},
foo3: { name: 'Mike', rep: 'Ray'}
}
My goal is do display both rep and name if there is rep and just display name 我的目标是如果有代表并且只显示名称,则同时显示代表和名称
JSX return JSX返回
if (rep) {
<b> {rep}(rep)</b>
<p>{name}<p/>
} else {
<b>{name}</b>
}
Assuming something like this 假设这样
{rep ? <b>{rep}(rep)</b><p>{name}</p> : <b>{name}</b> }
Your assumption is pretty good. 您的假设非常好。
You could do something like this: 您可以执行以下操作:
{rep ?
(
<div>
<b>{ rep } (rep)</b>
<p>{ name }</p>
</div>
)
: (
<b>{ name }</b>
)}
You can only return one HTML Element so you need to wrap the b
and p
tag into a div
. 您只能返回一个HTML元素,因此需要将
b
和p
标签包装到div
。
As @a_programmer pointed out in the comments: "With react 16/fiber you can also use <React.fragment>
instead of <div>
to keep the dom clean" 正如@a_programmer在评论中指出的那样:“使用react 16 / fiber,您还可以使用
<React.fragment>
而不是<div>
来保持dom干净”
Assuming you will always have the name you could do something like: 假设您将始终拥有该名称,则可以执行以下操作:
return(
<span>
{rep && <b>{rep}</b>}
<p>{name}</p>
</span>
)
Or if you don't: 或者,如果您不这样做:
return(
<span>
{rep && <b>{rep}</b>}
{name && <p>{name}</p>}
</span>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.