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:
- Ternary operator:
{isLoggedIn ? <Dashboard /> : <登录 />}— show one of two options. - Logical &&:
{hasError && <ErrorMessage />}— show something or nothing. - Early return: extract into a variable with an
如果statement before the return. - 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.
相关术语
相关资源
相关课程
- Conditional 渲染
学习模式 for conditional UI.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。