react八种条件渲染_在React应用程序中实现条件渲染的7种方法

react八种条件渲染

With React, we can build Single Page Applications that are dynamic and highly interactive. One way we fully utilize such interactivity is through conditional rendering.

借助React,我们可以构建动态且高度互动的单页应用程序。 我们充分利用这种交互性的一种方法是通过条件渲染。

Conditional rendering as a term describes the ability to render different UI markup based on certain conditions. In React-speak, it is a way to render different elements or components based on a condition. This concept is applied often in the following scenarios:

条件渲染一词描述了基于某些条件渲染不同的UI标记的能力。 在React-speak中,这是一种根据条件渲染不同元素或组件的方法。 此概念通常在以下情况下应用:

  • Rendering external data from an API

    从API渲染外部数据
  • Showing/hiding elements

    显示/隐藏元素
  • Toggling application functionality

    切换应用程序功能
  • Implementing permission levels

    实施权限级别
  • Authentication and Authorization

    认证与授权

In this article, we examine seven(7) ways to implement such conditional rendering in React applications.

在本文中,我们研究了在React应用程序中实现这种条件渲染的七种方法(7)。

挑战 ( The Challenge )

As a challenge, based on the value of isLoggedIn in our component state, we want to be able to display a Login button if the user isn’t logged in, and a Logout button if he/she is.

作为挑战,基于我们组件状态中isLoggedIn的值,如果用户未登录,我们希望能够显示一个Login按钮,如果他/她是用户,则希望显示一个Logout按钮。

This is what our starter component looks like:

这是我们的启动程序组件的外观:

Visually:

视觉上:

Code:

码:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoggedIn: true
    };
  }
  render() {
    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        <button>Login</button>
        <button>Logout</button>
      </div>
    );
  }
}


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Starter Code Fork this CodeSandBox to get started.

Starter Code Fork将此CodeSandBox入门。

START HERE 👉🏾 https://codesandbox.io/s/conditional\-rendering\-demo\-ei72f

在此处开始👉🏾https : //codesandbox.io/s/conditional\-rendering\-demo\-ei72f

Let’s Begin!

让我们开始吧!

解决方案 ( The Solution )

Please bear in mind that … within the code snippets implies that some code which isn’t directly connected with the point being explained goes there.

请记住,……在代码片段中表示某些与所解释的要点没有直接联系的代码就在那儿。

1.使用If…else语句 ( 1. Using an If…else Statement )

An if…else statement allows us to speficy that a particular action be carried out if a condition evaluates to true as well as do something else if it doesn’t. Using the sample project, we will examine two ways if…else conditions may be used to implement conditional rendering in React.

if…else语句使我们可以虚假地表示,如果条件为true ,则执行特定的操作,否则将执行其他操作。 使用示例项目,我们将研究两种方法, if…else条件可用于在React中实现条件渲染。

  • Extracting the conditional rendering into a function

    将条件渲染提取到函数中

In JSX, we are able to mix up JavaScript code with our markup to ensure stunning interactivity within our application. To do this we use a set of curly braces {} and write our JavaScript within. The caveat however is that there is a limit to what can be done within such braces. As a result the code snippet below would fail to achieve the desired result.

在JSX中,我们能够将JavaScript代码与标记混合在一起,以确保应用程序之间具有惊人的交互性。 为此,我们使用一组花括号{}并在其中编写我们JavaScript。 但是需要注意的是,在这种牙套中只能做些事情。 结果,下面的代码片段将无法获得所需的结果。

// index.js
...
render() {
    let {isLoggedIn} = this.state;
    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        {
          if(isLoggedIn){
            return <button>Logout</button>
          } else{
            return <button>Login</button>
          }
        }
      </div>
    );
}
...

To understand more about this behaviour, visit this link.

要了解有关此行为的更多信息,请访问此链接。

To solve this, we extract the conditional logic into a function as shown below:

为了解决这个问题,我们将条件逻辑提取到一个函数中,如下所示:

// index.js
...
render() {
    let {isLoggedIn} = this.state;
    const renderAuthButton = ()=>{
      if(isLoggedIn){
        return <button>Logout</button>
      } else{
        return <button>Login</button>
      }
    }
    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        {renderAuthButton()}
      </div>
    );
  }
...

Notice that we extract the logic from JSX into a function renderAuthButton. Thus, we only need to execute the function within the JSX curly braces.

注意,我们将逻辑从JSX提取到函数renderAuthButton 。 因此,我们只需要在JSX花括号内执行函数即可。

  • Multiple return statements.

    多个返回语句。

In using this method, the component must be kept as simple as possible to avoid a wasted re-render of sibling or parent components. As a result of this, we create a new functional component called AuthButton.

在使用此方法时,必须使组件尽可能简单,以避免浪费兄弟或父组件的重新渲染。 结果,我们创建了一个名为AuthButton的新功能组件。

// AuthButton.js

import React from "react";

const AuthButton = props => {
  let { isLoggedIn } = props;
  if (isLoggedIn) {
    return <button>Logout</button>;
  } else {
    return <button>Login</button>;
  }
};
export default AuthButton;

AuthButton returns various elements/components depending on the value of state that is passed down via the isLoggedIn props. Thus we import it in our index.js and pass down the appropriate state as shown below:

AuthButton返回各种元素/组件,具体取决于通过isLoggedIn道具传递的状态值。 因此,我们将其导入index.js并传递适当的状态,如下所示:

// index.js
...
import AuthButton from "./AuthButton";

...
  render() {
    let { isLoggedIn } = this.state;
    return (
      <div className="App">
      ...
        <AuthButton isLoggedIn={isLoggedIn} />
      </div>
    );
  }
...

You must avoid doing this:

您必须避免这样做:

// index.js
...
render() {
    let { isLoggedIn } = this.state;
    if (isLoggedIn) {
      return (
        <div className="App">
          <h1>
            This is a Demo showing several ways to implement Conditional
            Rendering in React.
          </h1>
          <button>Logout</button>;
        </div>
      );
    } else {
      return (
        <div className="App">
          <h1>
            This is a Demo showing several ways to implement Conditional
            Rendering in React.
          </h1>
          <button>Login</button>
        </div>
      );
    }
  }
}
...

The snippet above would achieve the same result but bloat the component unnecessarily while introducing performance issues as a result of constantly rerendering an unchanging component.

上面的代码片段将获得相同的结果,但由于不断重新渲染不变的组件而导致性能问题,而不必要地使组件过大。

2.使用元素变量 ( 2. Using Element Variables )

Element variables are an extension of **Extracting the conditional rendering into a function** as shown above. Element variables are simply variables that hold JSX elements. Thus we can conditionally assign elements/ components to these variables outside our JSX and only render the variable within JSX. See demo below:

元素变量是**Extracting the conditional rendering into a function**中的扩展**Extracting the conditional rendering into a function**如上所示。 元素变量只是保存JSX元素的变量。 因此,我们可以在JSX外部有条件地将元素/组件分配给这些变量,而仅在JSX内呈现变量。 请参见下面的演示:

// index.js
...
render() {
    let { isLoggedIn } = this.state;
    let AuthButton;
    if (isLoggedIn) {
      AuthButton = <button>Logout</button>;
    } else {
      AuthButton = <button>Login</button>;
    }
    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        {AuthButton}
      </div>
    );
  }
...

Notice how we conditionally assign values(components) to AuthButton and then we only have to render it neatly within our JSX.

请注意,我们是如何有条件地将值(组件)分配给AuthButton ,然后只需要在JSX中整齐地呈现它。

3.使用switch语句 ( 3. Using a Switch Statement )

As shown previously, we can conditionally return different markup from a component based on set conditions using an if…else statement. The same could be achieved with a switch statement where we can specify the markup for various conditions. See example below:

如前所示,我们可以使用if…else语句根据设置的条件有条件地从组件返回不同的标记。 使用switch语句可以达到相同的效果,在该语句中我们可以为各种条件指定标记。 请参见下面的示例:

// AuthButton.js
import React from "react";

const AuthButton = props => {
  let { isLoggedIn } = props;
  switch (isLoggedIn) {
    case true:
      return <button>Logout</button>;
      break;
    case false:
      return <button>Login</button>;
      break;
    default:
      return null;
  }
};
export default AuthButton;

Notice how we return various buttons based on the value of isLoggedIn. It is more reasonable to apply this method when there’s more than two possible values or outcomes. You may also do away with the break statement as the return statement automatically terminates the execution.

注意,我们如何基于isLoggedIn的值返回各种按钮。 当存在两个以上可能的值或结果时,应用此方法更为合理。 您也可以取消break语句,因为return语句会自动终止执行。

Note: Returning **null** from a component will cause it to hide itself/display nothing. This a good way to toggle visibility of components.

注意: 从组件 返回 **null** 会使它隐藏自身/不显示任何内容。 这是切换组件可见性的好方法。

4.三元运算符 ( 4. Ternary Operators )

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

条件(三元)运算符是唯一采用三个操作数JavaScript运算符。 该运算符通常用作if语句的快捷方式。

If you are familiar with ternary operators, then you are aware that is is simply a more concise way to write an if statement. Thus we have:

如果您熟悉三元运算符,那么您会知道这只是编写if语句的一种更简洁的方法。 因此,我们有:

// index.js
...
render() {
    let { isLoggedIn } = this.state;
    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        {isLoggedIn ? <button>Logout</button> : <button>Login</button>}
      </div>
    );
  }
...

In cases where, this approach makes the component bloated, bulky or less readable, you may encapsualte the conditional within a functional component as shown below:

在这种情况下,如果这种方法使组件膨胀,笨重或难以理解,则可以将条件封装在功能组件中,如下所示:

// AuthButton.js
import React from "react";

const AuthButton = props => {
  let { isLoggedIn } = props;
  return isLoggedIn ? <button>Logout</button> : <button>Login</button>;
};

export default AuthButton;

5.逻辑&&(使用&&进行短路评估) ( 5. Logical && (Short Circuit Evaluation with &&) )

Short circuit evaluation is a technique used to ensure that there are no side effects during the evaluation of eperands in an expression. The logical && helps us specify that an action should be taken only on one condition, otherwise, it would be ignored entirely. This is useful for situations where you only need to take an action when a certain condition is true, otherwise do nothing.

短路评估是一种用于确保评估表达式中的操作数时没有副作用的技术。 逻辑&&帮助我们指定仅应在一种情况下采取的措施,否则将被完全忽略。 这对于仅在特定条件为真时才需要采取措施,否则什么也不做的情况很有用。

For instance if we only needed to show the Logout button if the person is logged in, otherwise we do nothing. We’d have something like this:

例如,如果该人已登录,我们仅需要显示“ Logout按钮,否则我们什么也不做。 我们会有这样的事情:

// index.js
...
render() {
    let { isLoggedIn } = this.state;
    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        {isLoggedIn && <button>Logout</button>}
      </div>
    );
  }
...

This would display the logout button if isLoggedIn is true otherwise it’d display nothing. We could adapt this to fit our use case as shown below. However, it is not advisable.

如果isLoggedIntrue则将显示注销按钮,否则将不显示任何内容。 我们可以对此进行调整以适合我们的用例,如下所示。 但是,不建议这样做。

// index.js
...
return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        {isLoggedIn && <button>Logout</button>}
        {!isLoggedIn && <button>Login</button>}
      </div>
    );
  }
...

This would render the right button based on the value of isLoggedIn. However, this isn’t recommended as there are better, cleaner ways to achieve the same effect. Also this could easily make your code look messy and uninuitive once the component gets slightly larger.

这将基于isLoggedIn的值呈现右键。 但是,不建议这样做,因为有更好,更清洁的方法可以达到相同的效果。 而且,一旦组件稍大一些,这很容易使您的代码看起来混乱而单一。

6.使用立即调用的函数表达式(IIFE) ( 6. Using Immediately Invoked Function Expressions(IIFEs) )

Okay! Rememeber how we said JSX had limitations and wouldn’t be able to execute every JavaScript code? Well, this is isn’t entirely true as there are ways to bypass such behaviour. One such way is by using IIFEs.

好的! 记得我们怎么说JSX有局限性,无法执行所有JavaScript代码吗? 嗯,这不是完全正确的,因为有许多方法可以绕过这种行为。 一种方法是使用IIFE。

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. It’s used in the format below.

IIFE(立即调用函数表达式)是一种JavaScript函数,它在定义后立即运行。 它以以下格式使用。

(function () {
    statements
})();

You may learn more here.

您可以在此处了解更多信息

With this technique, we are able to to write conditional logic directly within JSX but wrapped within an anonymous function that is immediately invoked on evaluation of that portion of our code. See example below:

通过这种技术,我们能够直接在JSX内编写条件逻辑,但将其包装在匿名函数中,该匿名函数在评估该部分代码后立即被调用。 请参见下面的示例:

//index.js
...
render() {
    let { isLoggedIn } = this.state;
    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        {(function() {
          if (isLoggedIn) {
            return <button>Logout</button>;
          } else {
            return <button>Login</button>;
          }
        })()}
      </div>
    );
  }
...

This can also be written in a slightly more concise manner using an arrow function as shown below:

也可以使用箭头功能以更加简洁的方式编写该代码,如下所示:

// index.js
...
return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        {(()=> {
          if (isLoggedIn) {
            return <button>Logout</button>;
          } else {
            return <button>Login</button>;
          }
        })()}
      </div>
    );
  }
...

7.使用增强的JSX ( 7. Using Enhanced JSX )

Certain libaries expose functionality to extend JSX, thus making it possible to implement conditional rendering directly with JSX. One of such libraries is JSX Control Statements. It is a Babel plugin that transforms component-like control statements into their JavaScript counterparts during transpilation. See example below for how this may be implemented.

某些库公开了扩展JSX的功能,因此可以直接用JSX实现条件渲染。 此类库之一是JSX控制语句。 它是Babel插件,可在编译过程中将类似组件的控制语句转换为JavaScript对应的语句。 请参阅下面的示例以了解如何实现。

// index.js
...
return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering
          in React.
        </h1>
        <Choose>
          <When condition={isLoggedIn}>
             <button>Logout</button>;
          </When>
          <When condition={!isLoggedIn}>
             <button>Login</button>;
          </When>
        </Choose>
      </div>
    );
  }
...

This approach is however not recommended as the code you write is eventually transpiled to a regular JavaScript conditional. It is probably always better to just write JavaScript than add an extra dependency over something so trivial.

但是,不建议使用这种方法,因为您编写的代码最终会转换为常规JavaScript条件。 仅仅编写JavaScript可能总比对如此琐碎的事情增加额外的依赖要好。

性能问题 ( Performance Concerns )

As a general rule, it is best to ensure that in implemementing conditional rendering you:

作为一般规则,最好确保在实现条件渲染时:

  • Do not change the position of components arbitrarily in order to prevent components from unmounting and remounting unnecessarily.

    请勿随意更改组件的位置,以防止不必要地拆卸和重新安装组件。
  • Change only the markup that is concerned with the conditional rendering and leave out every other unchanging bit of the component.

    仅更改与条件渲染有关的标记,而忽略组件的所有其他不变的位。
  • Do not bloat your component unnecessarily within the render method, thus causing components to delay in rendering.

    不要在render方法中不必要地膨胀组件,从而导致组件延迟渲染。

For more on writing high performing conditionals in React, see this article by Cole Williams.

有关在React中编写高性能条件的更多信息,请参阅Cole Williams的这篇文章

结论 ( Conclusion )

We have successfully examined 7 ways to implement conditional rendering in React. Each method has it’s own advantage and the choice of which to use is mostly dependent on the use case. Things to consider include:

我们已经成功研究了在React中实现条件渲染的7种方法。 每种方法都有其自身的优势,使用哪种方法的选择主要取决于用例。 要考虑的事项包括:

  • The size of markup to be rendered conditionally

    有条件呈现的标记大小

  • The number of possible outcomes

    可能的结果数

  • Which would be more intuitive and readable

    Generally,I would recommend that:

    哪个会更直观和可读

    通常,我建议:

  • When there is only one expected outcome, the Logical && Operator comes in very handy.

    当只有一个预期的结果时, 逻辑&&运算符非常方便。
  • For boolean situations or use cases with only 2 possible outcomes, you may use If…else, Element variables, Ternary Operators and IIFEs.

    对于布尔型情况或只有两个可能结果的用例,可以使用If…else,Element变量,三元运算符和IIFE。
  • For cases of more than 2 outcomes, you may use a Switch statement, an extracted function or extracted functional component.

    如果结果超过2个,则可以使用Switch语句,提取的函数或提取的功能组件。

This is however merely a recommendation and the choice of which to go with is primarily yours.

但是,这仅是建议,与之搭配的选择主要是您的选择。

进一步阅读 ( Further Reading )

You may learn more via the following resources:

您可以通过以下资源了解更多信息:

翻译自: https://scotch.io/tutorials/7-ways-to-implement-conditional-rendering-in-react-applications

react八种条件渲染

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值