在 React 中,条件渲染能够通过多种形式,不同的应用形式场景取决于不同的上下文。 在本文中,咱们将探讨所有可用于为 React 中的条件渲染编写更好的代码的办法。

~~

条件渲染在每种编程语言(包含 javascript)中都是的常见性能。 在 javascript 中,咱们通常应用if else 语句,switch case语句和三元运算符编写条件渲染。

以上所有这些办法都实用于 React。 然而问题是,咱们如何能力无效地应用它们?

像你晓得的那样,React 具备 JSX 标记,通常咱们须要实现条件逻辑去管制组件。 然而,咱们不能在 JSX 中间接应用常见的 if elseswitch case语句。

在 JSX 中,咱们应该应用其余条件渲染办法,例如三元运算符和&&运算符。 在这里,咱们将探讨更多细节。

以下是我积攒的 7 种条件渲染办法,它们能够在 React 中应用。 每种形式在肯定的状况下都有本人的劣势。

目录

  • If Else条件渲染
  • 应用三元运算符进行条件渲染
  • &&运算符的条件渲染
  • switch case多条件渲染
  • 枚举对象的多条件渲染
  • HOC(高阶组件)条件渲染
  • 带有内部库的 JSX 条件渲染

1.If Else条件渲染

最佳实际概述

  • 在 JSX 标记之外的任何中央应用
  • 或者,如果你想在 if-else 块中执行多行代码

~~

这是所有程序员都能想到的第一个办法,即常见的 if-else语句。 咱们能够在 React 我的项目中的任何中央应用它。

在 React 中,如果要在 if 或者 else 块外部或 JSX 内部的任何中央执行多行代码,最好应用通用的 if-else 语句。

例如,如果用户登录,咱们想执行一些代码。

// * Conditional rendering with common if-else statement.if (isLoggedIn) {  setUserProfile(userData);  setUserHistory(userHistory);  // other block of codes;} 

或者,当你想基于用户角色定义可拜访的内容时。

if (userProfile.role === "superadmin") {  initSuperAdminFunction();  initSuperAdminComponent();  // other block of codes;} else if (userProfile.role === "admin") {  initAdminFunction();  initAdminComponent();  // other block of codes;} else {  initUserComponent();  // other block of codes;} 

如果你只想执行一行代码,例如在 if 或 else 块中调用函数,则能够删除括号。

if (userProfile.role === "superadmin") initSuperAdminComponent();else if (userProfile.role === "admin") initAdminFunction();else initUserComponent(); 

if-else 中不带括号的条件仅实用于其正下方的一行代码。

JSX 中的 if else 语句

你可能晓得,咱们能够在 JSX 中的方括号{}中注入和混合一些 javascript 代码。 然而它有一些局限性。

你不能间接向其中插入 if-else 语句。 在 JSX 中注入 if-else 语句仅实用于立刻调用函数表达式(IIFE),如下所示:

return (  <div>    {(() => {      if (isLoggedIn) {        return <div>I'm logged in.</div>;      }    })()}  </div>); 

如你所见,仅 if 语句就太简短了。 这就是为什么我不倡议在 JSX 中应用 if-else 语句的起因。

持续浏览 JSX 中还有其余一些条件渲染的办法。

  1. 应用三元运算符进行条件渲染

最佳实际概览

  • 条件变量或函数返回值赋值
  • 当你只想写一行代码来做条件判断
  • 于 JSX 中的条件渲染

三元运算符是常见 if-else 语句的快捷方式。 应用三元运算符,你能够在行内编写条件渲染,也能够只编写一行代码。

让咱们看一下条件渲染的变量值调配示例。

// Conditional rendering with common if elselet isDrinkCoffee;if (role === "programmer") {  isDrinkCoffee = true;} else {  isDrinkCoffee = false;}// Conditional rendering with ternary operatorlet isDrinkCoffee = role === "programmer" ? true : false; 

这是函数返回值的条件渲染示例:

// Conditional rendering with common if elsefunction isDrinkCoffee(role) {  if (role === "programmer") {    return true;  } else {    return false;  }}// Conditional rendering with ternary operatorfunction isDrinkCoffee(role) {  return role === "programmer" ? true : false;} 

如你所见, 你用了三元运算符,就用用一行代码来代替 if-else 语句。

你也能够在 JSX 中应用三元运算符,而不是将 if-else 与立刻调用函数表达式(IIFE)一起应用。

假如咱们要基于 isShow 状态有条件地渲染一个小组件。 您能够这样编写条件渲染。

return <div>{isShow ? <SmallComponent /> : null}</div>; 

if-else if-else应用三元运算符

在下面的示例中,我仅向你展现如何应用三元运算符替换 if-else 语句。

三元运算符还可用于替换多个条件渲染(if-else if-else)或嵌套的条件渲染。

然而,我不倡议你应用它,因为它比一般的 if-else语句更难读。

假如你要在 JSX 中实现嵌套的条件渲染。

return (  <div>    {condition_a ? (      <ComponentA />    ) : condition_b ? (      <ComponentB />    ) : condition_c ? (      <ComponentC />    ) : (      <ComponentD />    )}  </div>); 

看起来十分乱,是吧?

对于这种状况,应用 IIFE,switch-case 语句或枚举对象比三元运算符更好。

3.&&运算符的条件渲染

最佳实际概览

  • 应用它进行简略的条件渲染,不用去执行"else"块中的代码。

~~

应用三元运算符,能够缩短 if-else 语句的代码量,并为 JSX 中的条件渲染提供更好的抉择。

然而,你晓得有比三元运算符更简略的办法吗?

&&运算符可用于替换此类 if 语句。

// Instead of using ternary operator,{  isShow ? <SmallComponent /> : null;}// Use short-circuit && operator{  isShow && <SmallComponent />;} 

在三元运算符中,即便没有"else"条件,也须要写"null"表达式以防止语法错误。

应用&&运算符,你不须要写多余的代码。

然而,请记住,不能将&&运算符替换为if-else语句,更不用说if-else if-else语句了。

4.带 switch 的多条件渲染-案例

  • 能够在任何地位应用它来进行多个条件渲染,而只有一个变量能够判断条件。

~~

if-else语句一样,switch-case语句也是简直每种编程语言中的常见性能。

它用于具备雷同类型条件的多个条件渲染。

例如,咱们能够应用switch-case语句依据用户角色出现特定的变量值。

let welcomeMessage;switch (role) {  case "superadmin":    welcomeMessage = "Welcome Super Admin";  // you can put other codes here as well.  case "admin":    welcomeMessage = "Welcome Admin";  // you can put other codes here as well.  case "user":    welcomeMessage = "Welcome User";  // you can put other codes here as well.  default:    welcomeMessage = "Welcome Guest";  // you can put other codes here as well.} 

你还能够应用switch-case语句在 JSX 中进行条件渲染。 然而,你须要将其包装在 IIFE 中。

假如你要出现一个基于 alert 状态设置款式的alert组件。

return (  <div>    {(() => {      switch (status) {        case "warning":          return <AlertComponent status="warning" message={messageState} />;        case "error":          return <AlertComponent status="error" message={messageState} />;        case "success":          return <AlertComponent status="success" message={messageState} />;        default:          return <AlertComponent status="info" message={messageState} />;      }    })()}  </div>); 

你可能曾经留神到,两个示例都只有一个变量(rolestatus)来判断条件。 这就是我之前所说的雷同类型的条件。

switch-case语句不能用于解决简单和不同类型的条件。然而你能够应用通用的if-else if-else语句去解决那些场景。

5.枚举对象的多重条件渲染

  • 仅当您要调配具备多个条件的变量值或返回值时,才应用它。

~~

枚举对象还能够用于在 React 中实现多个条件渲染。 对于 JSX 标记中的 switch-case语句,它是更好的抉择。

如你所知,在第 5 种办法中,你应该将switch-case语句包装在 JSX 的 IIFE 中。 应用枚举对象,你不须要这样做。

让咱们用一个以前的一个示例来间隔。 你要基于状态出现 alert 组件。 这是应用枚举对象有条件地出现它的形式。

const ALERT_STATUS = {  warning: <AlertComponent status="warning" />,  error: <AlertComponent status="error" />,  success: <AlertComponent status="success" />,  info: <AlertComponent status="info" />,};return <div>{ALERT_STATUS[status]}</div>; 

你须要创立一个枚举对象,首先称为“ ALERT_STATUS”。 而后,只需在 JSX 中应用 []括号内的状态变量来调用它,该变量的值为'warning','error','success'或'info'。

如果须要传递其余道具或属性,则能够将 ALERT_STATUS 更改为这样的函数。

const ALERT_STATUS = (message) => ({  warning: <AlertComponent status="warning" message={message} />,  error: <AlertComponent status="error" message={message} />,  success: <AlertComponent status="success" message={message} />,  info: <AlertComponent status="info" message={message} />,});return <div>{ALERT_STATUS(messageState)[status]}</div>; 

你还能够将变量传递给 alert 组件。

let newVariable = ALERT_STATUS(messageState)[status]; 

当然,你应该首先定义枚举对象。

将枚举对象拆分到独自文件来复用

对于应用枚举对象进行条件渲染的最好的个性是能够复用。

回到示例案例,Alert 组件是 React 中通常可重用的组件。 因而,当你要有条件地渲染它时,也能够让它复用。

你能够在独自的文件中定义枚举,而后将它导出。

import React from "react";import AlertComponent from "./path/to/AlertComponent";export const ALERT_STATUS = (message) => ({  warning: <AlertComponent status="warning" message={message} />,  error: <AlertComponent status="error" message={message} />,  success: <AlertComponent status="success" message={message} />,  info: <AlertComponent status="info" message={message} />,}); 

而后,在要在组件中应用它时将其导入。

import { ALERT_STATUS } from "./alertStatus"; 

用法与以前雷同。

6.HOC 条件渲染

最佳做法摘要

  • 如果要在渲染组件之前实现或查看某些条件,请应用它。

~~

高阶组件(HOC)可用于在 React 中实现条件渲染。 当你要运行某些逻辑或在渲染组件之前进行查看时,能够应用它。

例如,你要在拜访某些组件之前检查用户是否已通过身份验证。

你能够应用 HOC 来爱护那些组件,而不是在每个须要身份验证的组件中编写if-else语句。

// This is Higher Order Componentimport React from "react";export default function withAuthentication(Component) {  // some code of authentication logic/service that result an isLoggedIn variable/state:  let isLoggedIn = true;  return function AuthenticatedComponent(props) {    if (isLoggedIn) {      return <Component {...props} />;    } else {      return <div class="alert alert-danger">You're not authenticated!</div>;    }  };} 

而后,您能够将其导入并在组件中应用。

import withAuthentication from "./withAuthentication"; 
const AuthenticatedUIComponent = withAuthentication(AnUIComponent);return (  <div>    <AuthenticatedUIComponent />  </div>); 

这样更棒了,是吗?

你能够将 HOC 用于其余可复用的条件渲染,例如加载指示器实现空值查看 等。

无关 HOC(具备性能组件)的更多详细信息,能够在 medium (https://medium.com/@albertchu539/higher-order-components-in-a-react-hooks-world-69fe1f0b0791)。

7.带有内部库的 JSX 条件渲染

最佳做法摘要

  • 防止应用此办法。 相熟下面的 6 种办法:D

只管我不倡议你应用此办法,但我只是想让你晓得,有一个 babel 插件使 JSX 具备本人的条件渲染标记。

应用 JSX 管制语句,您能够像这样在 JSX 中编写条件渲染。

<If condition={test}>  <span>Truth</span></If>;<Choose>  <When condition={test1}>    <span>IfBlock</span>  </When>  <When condition={test2}>    <span>ElseIfBlock</span>    <span>Another ElseIfBlock</span>    <span>...</span>  </When>  <Otherwise>    <span>ElseBlock</span>  </Otherwise></Choose>; 

在编译中,这些标签将转换为三元运算符。

一些开发人员应用此插件,因为它对于 JSX 中的条件渲染看起来更具可读性。

~~

译者注: 你还能够实现一个简略的 IF 组件来实现简略的判断。

const If = (props) => {  const condition = props.condition || false;  const positive = props.then || null;  const negative = props.else || null;  return condition ? positive : negative;}; 
<IF condition={isLoggedIn} then={<Hello />} else={<div>请先登录</div>} /> 

这就是你能够在 React 中用于条件渲染的所有 7 种办法。

编码欢快!

译文来自 https://dev.to/syakirurahman/react-conditional-rendering-best-practices-with-7-different-methods-16e3#6_Conditional_Rendering_with_HOC

原作者 Syakir Rahman

译者: 蓝色的秋风(github/hua1995116)

最初

如果我的文章有帮忙到你,心愿你也能帮忙我,欢送关注我的微信公众号 秋风的笔记,回复好友 二字,可加微信并且退出交换群,秋风的笔记 将始终陪伴你的左右。

也能够扫码加我微信好友,进交换群。