条件渲染允许我们根据特定的条件来控制用户界面(UI)的显示内容。这在根据用户输入、数据状态或系统状态来显示或隐藏元素时非常有用。这种机制有助于保持界面的相关性和对变化的响应能力。
- 根据当前状态或 props 显示不同的 UI 元素。
- 当数据或条件发生变化时,自动更新用户看到的内容。
- 无需手动操作 DOM 来显示或隐藏内容。
条件渲染的实现方式
1. 使用 If/Else 语句
If/else 语句允许我们根据条件渲染不同的组件。这种方法适用于处理复杂的条件逻辑。
!<a href="https://media.geeksforgeeks.org/wp-content/uploads/20250813154119841082/ifelse.webp">ifelse
function Item({ name, isPacked }) {
if (isPacked) {
return {name} ;
}
return {name} ;
}
- 如果 isPacked 为 true,它将显示:Space Suit
- 如果 isPacked 为 false,它将显示:Space Suit
2. 使用三元运算符
三元运算符(condition ? expr1: expr2)是一种有条件地渲染 JSX 元素的简洁方法。当逻辑简单且只有两个渲染选项时,通常会使用这种方法。
!<a href="https://media.geeksforgeeks.org/wp-content/uploads/20250813154224712902/ternaryoperatororconditionaloperator.webp">ternaryoperatororconditionaloperator
function Greeting({ isLoggedIn }) {
return {isLoggedIn ? "Welcome Back!" : "Please Sign In"}
;
}
- 如果 isLoggedIn 为 true:Welcome Back!
- 如果 isLoggedIn 为 false:Please Sign In
3. 使用逻辑与 (&&) 运算符
当第一个操作数为 true 时,&& 运算符会返回第二个操作数;如果为 false,则不返回任何内容。当我们只想在某个条件为真时渲染内容时,这非常有用。
function Notification({ hasNotifications }) {
return {hasNotifications && You have new notifications!
};
}
- 如果 hasNotifications 为 true:You have new notifications!
- 如果 hasNotifications 为 false:不会渲染任何内容。
4. 使用 Switch Case 语句
当我们需要处理多个条件时,switch case 语句 会非常有用,否则可能需要编写多个 if 条件。如果需要检查的条件很多,这种方法可能会更具可读性。
!<a href="https://media.geeksforgeeks.org/wp-content/uploads/20250813154316582037/switchstatement.webp">switchstatement
function StatusMessage({ status }) {
switch (status) {
case ‘loading‘:
return Loading...
;
case ‘success‘:
return Data loaded successfully!
;
case ‘error‘:
return Error loading data.
;
default:
return Unknown status
;
}
}
- 如果 status 是 ‘loading‘:Loading…
- 如果 status 是 ‘success‘:Data loaded successfully!
- 如果 status 是 ‘error‘:Error loading data.
5. 列表中的条件渲染(使用 .map())
在根据条件渲染项目列表时,条件渲染非常有帮助。我们可以对数组进行过滤或映射,以便根据条件选择性地渲染组件。
const items = ["Apple", "Banana", "Cherry"];
const fruitList = items.map((item, index) =>
item.includes("a") ? {item}
: null
);
如果项目包含字母 "a",它将被显示。
6. 基于组件状态的条件渲染
我们还可以根据组件的状态来管理条件渲染。例如,我们可以显示一个加载中的旋转图标,直到获取到数据,然后一旦数据准备好就显示实际内容。
语法:
if (loading) {
// Render Loading Component
} else {
// Render Data Component
}
条件渲染的实际应用案例
1. 基于身份验证显示用户资料
我们可以根据用户是否登录来有条件地渲染用户的资料页面,如果未登录则显示登录表单。
JavaScript
CODEBLOCK_c5da6c7e
输出示例
在这个例子中
- 组件使用 useState 来管理 isAuthenticated 状态,该状态最初设置为 false。
- isAuthenticated 状态决定了渲染的内容:如果为 false,则显示 "Log In" 按钮;如果为 true,则显示 "User Profile" 标题。