react 条件渲染_使用三元和逻辑AND在React中进行条件渲染

本文介绍了在React中如何使用三元运算符和逻辑AND进行条件渲染。通过比较三元与if/else,以及三元与逻辑AND,阐述它们在不同情况下的适用性。文章提醒在使用逻辑AND时要注意非布尔值可能导致的意外渲染问题,并提供了防止这种情况的解决策略。
摘要由CSDN通过智能技术生成

react 条件渲染

by Donavon West

由Donavon West

使用三元和逻辑AND在React中进行条件渲染 (Conditional Rendering in React using Ternaries and Logical AND)

There are several ways that your React component can decide what to render. You can use the traditional if statement or the switch statement. In this article, we’ll explore a few alternatives. But be warned that some come with their own gotchas, if you’re not careful.

您的React组件可以通过几种方式来决定渲染什么。 您可以使用传统的if语句或switch语句。 在本文中,我们将探讨一些替代方案。 但请注意,如果您不小心,某些工具会带有自己的陷阱。

三元vs如果/其他 (Ternary vs if/else)

Let’s say we have a component that is passed a name prop. If the string is non-empty, we display a greeting. Otherwise we tell the user they need to sign in.

假设我们有一个传递name道具的组件。 如果字符串非空,则显示问候语。 否则,我们会告诉用户他们需要登录。

Here’s a Stateless Function Component (SFC) that does just that.

这是一个无状态功能组件(SFC),它就是这样做的。

const MyComponent = ({ name }) => {  if (name) {    return (      <div className="hello">        Hello {name}      </div>    );  }  return (    <div className="hello">      Please sign in    </div>  );};

Pretty straightforward. But we can do better. Here’s the same component written using a conditional ternary operator.

非常简单。 但是我们可以做得更好。 这是使用条件三元运算符编写的相同组件。

const MyComponent = ({ name }) => (  <div className="hello">    {name ? `Hello ${name}` : 'Please sign in'}  </div>);

Notice how concise this code is compared to the example above.

请注意,与上面的示例相比,此代码有多简洁。

A few things to note. Because we are using the single statement form of the arrow function, the return statement is implied. Also, using a ternary allowed us to DRY up the duplicate <div className="hello"> markup. ?

需要注意的几件事。 因为我们使用的是箭头函数的单条语句形式,所以隐含了return语句。 另外,使用三元数使我们能够干燥重

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值