条件渲染与列表
约 396 字大约 1 分钟
布欧-Lewyon
2026-05-15
条件渲染
function Greeting({ isLoggedIn }: { isLoggedIn: boolean }) {
// 方式一:&&
return <div>{isLoggedIn && <p>Welcome back!</p>}</div>
// 方式二:三元表达式
return <div>{isLoggedIn ? <p>Welcome</p> : <p>Please login</p>}</div>
// 方式三:if/else 辅助函数
if (isLoggedIn) return <Dashboard />
return <LoginPage />
}&& 陷阱
// ❌ 错误:count=0 渲染出 "0"
{count && <p>Count: {count}</p>}
// ✅ 正确:转为布尔值
{count > 0 && <p>Count: {count}</p>}
{!!count && <p>Count: {count}</p>}列表渲染
interface Todo {
id: number
text: string
done: boolean
}
function TodoList() {
const todos: Todo[] = [
{ id: 1, text: 'Learn React', done: true },
{ id: 2, text: 'Build a project', done: false },
]
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
<span>{todo.done ? '✅' : '⬜'} {todo.text}</span>
</li>
))}
</ul>
)
}Key 的重要性
// ✅ 用唯一 ID
{todos.map(todo => <TodoItem key={todo.id} todo={todo} />)}
// ❌ 不要用 index(列表变化时导致性能问题和 BUG)
{todos.map((todo, index) => <TodoItem key={index} todo={todo} />)}Key 帮助 React 识别哪些项被修改、添加或删除。使用 index 会导致:
- 列表项顺序变化时,DOM 顺序错乱。
- 输入框内容错位。
样式方案
// 1. 内联样式
const style = { color: 'red', fontSize: '16px' }
<div style={style}>Hello</div>
// 2. CSS Module
import styles from './Button.module.css'
<button className={styles.primary}>Click</button>
// 3. CSS-in-JS(styled-components)
import styled from 'styled-components'
const StyledButton = styled.button`
background: blue;
color: white;
padding: 8px 16px;
`
<StyledButton>Click</StyledButton>小结
- 条件渲染:
&&(注意 falsy 值)、三元、if/else。 - 列表渲染:
map()+key(用唯一 ID,不用 index)。 - 样式:内联 / CSS Module / CSS-in-JS 三种方式。
key帮助 React 高效 Diff,用 index 会引起 Bug。
上一节:Props 与事件处理 下一节:useState 与状态管理
