Skip to content

Conditional 渲染

Showing and hiding UI 使用如果语句, ternary 运算符, and logical AND 运算符.

你将学到

  • Using ternary 运算符 for 如果-else 渲染
  • Using logical AND (&&) for show-or-hide 渲染
  • Extracting 条件到 变量 for readability
  • Returning 空到 渲染无

概念讲解

Rendering Based on Conditions

In React, conditional rendering means showing different UI based on the current state or props. Because JSX is JavaScript, you can use standard JavaScript conditional patterns directly in your JSX. There is no special template directive like *ngIf in Angular or v-如果 in Vue — you use plain JavaScript.

The Ternary Operator

The ternary operator 条件 ? 真 : 假 is the most common pattern for if-else rendering in JSX. For example, {isLoggedIn ? <Dashboard /> : <登录 />} shows the dashboard for logged-in users and the login form otherwise. The ternary is an expression (it returns a value), which is why it works inside JSX curly braces. Keep ternaries shallow — deeply nested ternaries are hard to read.

Logical AND (&&)

The logical AND operator && is useful for show-or-hide rendering where there is no else branch. {hasError && <ErrorMessage />} renders the error message only when hasError is true. Be careful: if the left side is 0 or an empty string, React will render that value. Always ensure the left side is a boolean, or use {!!值 && <组件 />} to coerce to boolean.

Returning null

Sometimes the cleanest approach is to return null from a component when it should not render anything. This is useful when the condition is complex or when a component should entirely hide itself. You can also extract conditions into variables above the return statement for readability: const showHeader = isLoggedIn && hasProfile; then {showHeader && <Header />}.

Element Variables

You can store JSX elements in variables and conditionally include them. This is useful when the branches are complex: let button = <LoginButton />; 如果 (isLoggedIn) button = <LogoutButton />; then use {button} in your JSX. This keeps the return statement clean and the logic readable. For more complex conditions, consider extracting the conditional rendering into a separate sub-component that encapsulates the logic.

示例代码

              import { useState } from "react";

function UserGreeting({ user }) {
  // Extract conditions into variables for readability.
  const showAdminPanel = user?.role === "admin";
  const hasUnreadMessages = user?.unreadCount > 0;

  return (
    <div>
      {/* Ternary for if-else rendering */}
      {user ? (
        <h1>Welcome back, {user.name}!</h1>
      ) : (
        <h1>Please sign in.</h1>
      )}

      {/* Logical AND for show-or-hide */}
      {showAdminPanel && <AdminPanel />}

      {/* Coerce to boolean to avoid rendering 0 */}
      {!!hasUnreadMessages && (
        <p>You have {user.unreadCount} unread messages.</p>
      )}
    </div>
  );
}
            

Three 模式: ternary for 如果-else, && for show-or-hide, and !! 到 coerce 到布尔值. Extracting 条件到 变量 keeps JSX readable.

动手试一试

  • JSON Formatter

    Inspect 数据那个 drives 你的 conditional 渲染 logic.

  • Code Minifier

    See 如何 conditional 渲染编译 and minifies.

常见错误

错误写法

Using && 使用数字那个渲染 0 on screen

正确做法

如果左 边的 && 是 0, React 渲染 '0'. Coerce 到布尔值使用 !!值 or use ternary: 值 > 0 ? <组件 /> : 空.

错误写法

Nesting ternary 运算符也 deeply

正确做法

Deeply nested ternaries 是 unreadable. Extract 到变量, use helper 函数, or lookup 对象/映射. Keep JSX 表达式 flat and 清晰.

练习 Conditional 渲染

8 个练习

练习 Conditional 渲染

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误