Appearance
条件渲染 & 列表渲染
React 基础速成
在 React 和 React Native 中,渲染是构建用户界面的核心过程。条件渲染和列表渲染是两种常用的渲染技术,它们允许我们根据数据动态地生成 UI。
1. 条件渲染
条件渲染是指根据条件决定是否渲染某个组件或元素。
基本语法
使用三元运算符
jsx
import { View, Text } from 'react-native';
import { useState } from 'react';
export default function ConditionalRendering() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<View>
{isLoggedIn ? (
<Text>Welcome back!</Text>
) : (
<Text>Please log in.</Text>
)}
<Button
title={isLoggedIn ? 'Log Out' : 'Log In'}
onPress={() => setIsLoggedIn(!isLoggedIn)}
/>
</View>
);
}使用逻辑与运算符
当你只需要在条件为真时渲染某个元素,可以使用逻辑与运算符:
jsx
import { View, Text } from 'react-native';
import { useState } from 'react';
export default function ConditionalRendering() {
const [isLoading, setIsLoading] = useState(true);
return (
<View>
{isLoading && <Text>Loading...</Text>}
{!isLoading && <Text>Content loaded!</Text>}
</View>
);
}使用 if 语句
在函数组件的主体中,你可以使用 if 语句来决定渲染什么:
jsx
import { View, Text } from 'react-native';
import { useState } from 'react';
export default function ConditionalRendering() {
const [userType, setUserType] = useState('guest');
let content;
if (userType === 'admin') {
content = <Text>Welcome, Admin!</Text>;
} else if (userType === 'user') {
content = <Text>Welcome, User!</Text>;
} else {
content = <Text>Welcome, Guest!</Text>;
}
return (
<View>
{content}
</View>
);
}条件渲染的应用场景
- 用户认证状态:根据用户是否登录显示不同的内容
- 加载状态:在数据加载过程中显示加载指示器
- 错误状态:当出现错误时显示错误信息
- 空状态:当数据为空时显示空状态提示
- 权限控制:根据用户权限显示不同的功能
2. 列表渲染
列表渲染是指根据数组数据生成一系列的组件或元素。
使用 map 方法
jsx
import { View, Text } from 'react-native';
export default function ListRendering() {
const items = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
return (
<View>
{items.map((item, index) => (
<Text key={index}>{item}</Text>
))}
</View>
);
}使用 key 属性
在渲染列表时,每个元素都应该有一个唯一的 key 属性,这有助于 React 识别哪些元素发生了变化:
jsx
import { View, Text } from 'react-native';
export default function ListRendering() {
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
return (
<View>
{users.map((user) => (
<Text key={user.id}>{user.name}</Text>
))}
</View>
);
}使用 FlatList 组件
在 React Native 中,对于大型列表,推荐使用 FlatList 组件,它提供了性能优化:
jsx
import { FlatList, Text, View } from 'react-native';
export default function FlatListExample() {
const data = [
{ id: '1', title: 'Item 1' },
{ id: '2', title: 'Item 2' },
{ id: '3', title: 'Item 3' },
{ id: '4', title: 'Item 4' },
{ id: '5', title: 'Item 5' }
];
const renderItem = ({ item }) => (
<View style={{ padding: 20 }}>
<Text>{item.title}</Text>
</View>
);
return (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item) => item.id}
/>
);
}使用 SectionList 组件
对于分组的列表,可以使用 SectionList 组件:
jsx
import { SectionList, Text, View } from 'react-native';
export default function SectionListExample() {
const sections = [
{
title: 'Fruits',
data: ['Apple', 'Banana', 'Cherry']
},
{
title: 'Vegetables',
data: ['Carrot', 'Broccoli', 'Spinach']
}
];
const renderItem = ({ item }) => (
<View style={{ padding: 10 }}>
<Text>{item}</Text>
</View>
);
const renderSectionHeader = ({ section }) => (
<View style={{ padding: 10, backgroundColor: '#f0f0f0' }}>
<Text style={{ fontWeight: 'bold' }}>{section.title}</Text>
</View>
);
return (
<SectionList
sections={sections}
renderItem={renderItem}
renderSectionHeader={renderSectionHeader}
keyExtractor={(item, index) => index.toString()}
/>
);
}3. 常见错误与解决方案
错误 1:忘记添加 key 属性
错误:
jsx
import { View, Text } from 'react-native';
export default function ListRendering() {
const items = ['Apple', 'Banana', 'Cherry'];
return (
<View>
{items.map((item) => (
<Text>{item}</Text> // 错误:缺少 key 属性
))}
</View>
);
}解决方案:
jsx
import { View, Text } from 'react-native';
export default function ListRendering() {
const items = ['Apple', 'Banana', 'Cherry'];
return (
<View>
{items.map((item, index) => (
<Text key={index}>{item}</Text> // 正确:添加了 key 属性
))}
</View>
);
}错误 2:使用不稳定的 key
错误:
jsx
import { View, Text } from 'react-native';
export default function ListRendering() {
const items = ['Apple', 'Banana', 'Cherry'];
return (
<View>
{items.map((item, index) => (
<Text key={Math.random()}>{item}</Text> // 错误:使用了不稳定的 key
))}
</View>
);
}解决方案:
jsx
import { View, Text } from 'react-native';
export default function ListRendering() {
const items = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
];
return (
<View>
{items.map((item) => (
<Text key={item.id}>{item.name}</Text> // 正确:使用了稳定的 key
))}
</View>
);
}错误 3:在条件渲染中使用 if 语句
错误:
jsx
import { View, Text } from 'react-native';
import { useState } from 'react';
export default function ConditionalRendering() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<View>
if (isLoggedIn) {
<Text>Welcome back!</Text> // 错误:在 JSX 中使用 if 语句
}
</View>
);
}解决方案:
jsx
import { View, Text } from 'react-native';
import { useState } from 'react';
export default function ConditionalRendering() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<View>
{isLoggedIn && <Text>Welcome back!</Text>} // 正确:使用逻辑与运算符
</View>
);
}4. 最佳实践
1. 条件渲染最佳实践
- 使用三元运算符:对于简单的二选一渲染
- 使用逻辑与运算符:对于仅在条件为真时渲染
- 使用 if 语句:对于复杂的条件逻辑
- 提取条件渲染为组件:对于复杂的条件渲染,将其提取为单独的组件
2. 列表渲染最佳实践
- 使用唯一的 key:为列表中的每个元素提供唯一的 key
- 使用 FlatList:对于大型列表,使用 FlatList 提高性能
- 使用 SectionList:对于分组的列表,使用 SectionList
- 优化渲染性能:对于复杂的列表项,使用 React.memo 避免不必要的重新渲染
- 分页加载:对于非常大的列表,实现分页加载
3. 性能优化
- 避免在渲染过程中计算:将复杂的计算移到渲染函数之外
- 使用 useMemo:缓存计算结果
- 使用 useCallback:缓存事件处理函数
- 虚拟滚动:对于长列表,使用 FlatList 的虚拟滚动功能
5. 总结
条件渲染和列表渲染是 React 和 React Native 中常用的渲染技术:
- 条件渲染:根据条件决定是否渲染某个组件或元素
- 列表渲染:根据数组数据生成一系列的组件或元素
掌握这些渲染技术,你可以创建出更加动态、交互性更强的 React Native 应用。
在使用这些技术时,要注意:
- 为列表项提供唯一的 key 属性
- 避免在 JSX 中使用 if 语句
- 对于大型列表,使用 FlatList 或 SectionList
- 优化渲染性能,避免不必要的重新渲染
下一节,我们将学习事件处理,这是 React 中处理用户交互的核心概念。
