简体   繁体   English

在 React 中显示的条件渲染

[英]conditional rendering to display in React

在此处输入图像描述

I wanted to display badge/text after which condition is met from two conditions.我想显示徽章/文本,然后满足两个条件。 First condition is that if no openSopts available then show SOLD OUT badge/text and if this condition is not met then check if it is online and then show badge/text of ONLINE .第一个条件是,如果没有可用的openSopts ,则显示SOLD OUT徽章/文本,如果不满足此条件,则检查它是否在线,然后显示ONLINE的徽章/文本。 But badge/text is not shown on card component, can you please tell me what mistake i am doing ?但是卡片组件上没有显示徽章/文字,你能告诉我我在做什么错误吗?

The JSX being returned does not include the JSX in your if / else statement.返回的 JSX 不包括您的if / else语句中的 JSX。 It needs to be part of the JSX that's returned in order for it to show up.它必须是返回的 JSX 的一部分才能显示出来。

You could use ternary expressions to do it like this (add this to the JSX after your return statement, put it wherever you'd like the badge rendered):您可以使用三元表达式来执行此操作(在您的return语句之后将其添加到 JSX,将其放在您希望呈现徽章的任何位置):

{ props.openSpots === 0 ? <div className="card--badge">SOLD OUT</div> : null }
{ props.openSpots > 0 && props.location === "Online" ? <div className="card--badge">Online</div> : null }

You could nest them if you wanted a single statement, but that starts to get difficult to read :如果你想要一个语句,你可以嵌套它们,但这开始变得难以阅读

{
   props.openSpots === 0 
      ? <div className="card--badge">SOLD OUT</div> 
      : props.location === "Online" 
         ? <div className="card--badge">Online</div> 
         : null
}

You are not using the JSX in the rendering part, its just a statement.您没有在渲染部分使用 JSX,它只是一个声明。

Either save the JSX in variable like this:将 JSX 保存在变量中,如下所示:

let badge = null

if (openSpots === 0) {
badge = ..
} else if (..) {
badge = ..
}

// Use it in code 

...
<div class="card-badge">{badge}</div>

Or use conditional rendering inline或者使用条件渲染内联

Just assign your code piece to a variable and then render it wherever you want.😊只需将您的代码段分配给一个变量,然后在您想要的任何地方渲染它。😊

...
const badge = openSpots === 0 ? <div className="card--badge">SOLD OUT</div> : <div className="card--badge">Online</div>
...
return (
  <div>
   {badge}
  </div>
);

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

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