优雅的处理react jsx 中的条件判断

5,153 阅读1分钟
原文链接: xixitoday.com

jsx的{}只能是表达式,为了增强代码可读性,下面介绍如何处理jsx 中的条件判断。

Conditionals in JSX

使用短路与&&代替三元运算符实现元素的条件显示

实际业务中,只有满足条件时,有些元素才会显示。例如页面loading。
推荐使用短路与实现:

//Instead of  `? :`
const Loading = (isloading) => {
  return isloading && <div>Loading~</div>;
};

使用子组件或 IIFE(立即执行函数)实现复杂的条件判断

业务场景较为复杂时,需在jsx 中进行多层的条件判断。jsx 的{}中只能是表达式,若使用多个三元运算符会降低代码的可读性。推荐拆分子组件或采用IIFE的形式。

复杂场景举例:

// Y soo many ternary??? :-/
const sampleComponent = () => {
  return (
    <div>
      {flag && flag2 && !flag3
        ? flag4
        ? <p>Blah</p>
        : flag5
        ? <p>Meh</p>
        : <p>Herp</p>
        : <p>Derp</p>
      }
    </div>
  )
};

  1. 拆分子组件:

    const SubComponent = (flag, flag2, flag3, flag4, flag5) => {
        if (flag && flag2 && !flag3) {
            if (flag4) {
                return <p>Blah</p>
            } else if (flag5) {
                return <p>Meh</p>
            } else {
                return <p>Herp</p>
            }
        } else {
            return <p>Derp</p>
        }
    }
    const sampleComponent = () => {
        return <div>
            <SubComponent {...conditions} />
        </div>;
    }
  2. IIFE:

    const sampleComponent = () => {
      return (
        <div>
          {
            (() => {
              if (flag && flag2 && !flag3) {
                if (flag4) {
                  return <p>Blah</p>
                } else if (flag5) {
                  return <p>Meh</p>
                } else {
                  return <p>Herp</p>
                }
              } else {
                return <p>Derp</p>
              }
            })()
          }
        </div>
      )
    };
发布于  tags:
  • { react-tips }