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="hell
o"> markup. ?
需要注意的几件事。 因为我们使用的是箭头函数的单条语句形式,所以隐含了return
语句。 另外,使用三元数使我们能够干燥重