In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to use ternary expressions in React conditional rendering". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Ternary expression vs if/else
Suppose we have a component passed in a name attribute. If the string is not empty, we will display a greeting. Otherwise, we will tell users that they need to log in.
This is a stateless functional component (SFC) that only implements the above functions.
Const MyComponent = ({name}) = > {if (name) {return (Hello {name});} return (Please sign in);}
It's simple, but we can do better. This is the same component written using the ternary operator conditional ternary operator.
Const MyComponent = ({name}) = > ({name? `Hello ${name} `: 'Please sign in'})
Notice how concise this code is compared to the example above.
There are a few points to pay attention to. Because we use the single-statement form of the arrow function, the return statement is implied. In addition, the use of ternary operators allows us to omit duplicate tags.
Ternary expression vs & &
As you can see, ternary expressions are very good for expressing if/else conditionals. But what about the simple if condition?
Let's look at another example. If isPro (a Boolean value) is true, we will display a trophy emoji. We also want to render the number of stars (if not 0). We can write like this.
Const MyComponent = ({name, isPro, stars}) = > (Hello {name} {isPro? '♨': null} {stars? (Stars: {'☆' .repeat (stars)}): null})
Notice that the else condition returns null. This is because the ternary expression must have an "otherwise" condition.
For simple if conditionals, we can use something more appropriate: the & operator. This is the same code written with & &.
Const MyComponent = ({name, isPro, stars}) = > (Hello {name} {isPro & & '♨'} {stars & & (Stars: {'☆' .repeat (stars)})})
There is not much difference, but notice that we have eliminated the null (else conditional) of each ternary expression. Everything should be rendered as before.
Hey! Hey! What did John get? When nothing should be rendered, there is only a 0. This is the trap I mentioned above. Here's an explanation for why:
According to MDN, a logical operator "and" (that is, & &):
Expr1 & & expr2
If expr1 can be converted to false, return expr1; otherwise return expr2. Thus, when used with Boolean values, true is returned if both operands are true,&&; otherwise, false is returned.
OK, before you start pulling your hair, let me explain it to you.
In our example, expr1 is the variable stars, whose value is 0, because 0 is a false value, 0 is returned and rendered. Look, it's not so bad.
I will simply write this.
Returns expr1 if expr1 is a false value, expr2 otherwise.
So, when using & & for non-Boolean values, we have to get this false value to return something that React cannot render, such as the value false.
We can achieve this goal in several ways. Let's try it.
{! stars & & ({'☆' .repeat (stars)})}
Notice the double exclamation operator (!!) before stars. (well, there is no double exclamation operator. We only used the exclamation operator twice).
* an exclamation operator forces the value of stars to become a Boolean and perform a "no" operation. If stars is 0, then! stars will be true.
Then we perform the second non-operation, so if stars is 0, it will be false. That's exactly what we want.
If you don't like it, you can also force a Boolean number, such as this (which I think is a bit lengthy).
{Boolean (stars) & & (
Or just use a comparator to produce a Boolean value (some would say this is even more semantic).
{stars > 0 & & (about strings
Empty strings have the same problem as numbers. But because the rendered empty string is invisible, this is not the kind of problem you are likely to deal with and may not even notice it. However, if you are a fanatic and do not want empty strings on DOM, you should take the precautions we have taken for numbers above.
Other solutions
One possible solution that can be extended to other variables in the future is to create a separate shouldRenderStars variable. Then you use & & to deal with Boolean values.
Const shouldRenderStars = stars > 0 return ({shouldRenderStars & & ({'☆' .repeat (return)}))
Then, in the future, if business rules require you to log in, own a dog and drink light beer, you can change the way shouldRenderStars is obtained, while the content returned remains the same. You can also put this logic in other testable places and keep the rendering clear.
Const shouldRenderStars = stars > 0 & & loggedIn & & pet = = 'dog' & & beerPref =' Light`; return ({shouldRenderStars & & ({'☆' .repeat (stars)})}); "how to use ternary expressions in React conditional rendering" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.