美文网首页
[React] Conditional Rendering

[React] Conditional Rendering

作者: JellyL | 来源:发表于2017-07-10 22:59 被阅读20次

We always use the follow two ways to conditional render in JSX:

  • Ternary(Conditional) operator
render() {
    return (
      <div>  
        xxx
        <div>{ shouldShow ? 'Hey' : null }</div>
        xxx
      </div>
    );
  }
  • Logical conjunction
render() {
    return (
      <div>  
        xxx
        <div>{ shouldShow && 'Hey'}</div>
        xxx
      </div>
    );
  }

false, null, undefined, and true are valid children. They will be ignored( and skips the second expression), and simply don't render. These JSX expressions will all render to the same thing:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

This JSX only renders the string Hey only when shouldShow is true:

And one thing special is that, when shouldShow is an integer 0:

For ternary operator, it will not render any thing.
For logical conjunction, it will rend an integer 0 there.

Actually, there are multiple ways to conditional show, if you are interesting with them, checkout them here.
if statement
ternary operation
logical && operator
switch case operator
enums
Multi-Level Conditional Rendering
With Higher Order Components
External Templating Components

相关文章

网友评论

      本文标题:[React] Conditional Rendering

      本文链接:https://www.haomeiwen.com/subject/lsnuhxtx.html