Skip to content

Conditional 渲染

一句话解释

Conditional 渲染平均值 showing 不同 JSX based on 条件 — using 如果语句, ternary 运算符, or logical &&.

用大白话说

Conditional rendering is how you show or hide parts of the UI based on state or props. React gives you several patterns:

  1. Ternary operator: {isLoggedIn ? <Dashboard /> : <登录 />} — show one of two options.
  2. Logical &&: {hasError && <ErrorMessage />} — show something or nothing.
  3. Early return: extract into a variable with an 如果 statement before the return.
  4. Switch statement: for multiple mutually exclusive options.

All of these work because JSX is JavaScript — you can use any JS expression inside curly braces. The key rule is that every branch must return valid JSX (or 空 to render nothing).

示例

jsx
function Greeting({ isLoggedIn, name }) {
  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome back, {name}!</h1>
      ) : (
        <h1>Please sign in.</h1>
      )}
    </div>
  );
}

ternary 运算符选择之间 welcome 消息 and sign-in prompt based on isLoggedIn.

相关术语

相关资源

相关课程

解读错误信息

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

查看错误

← 返回术语表