如何在React Native中实现同一组件的多次复用
React Native 可复用卡片列表实现方案
核心实现逻辑为封装通用卡片组件 + 列表组件遍历数据渲染,仅需写一次卡片组件代码即可适配所有条目。
1. 封装通用卡片组件
新建独立的卡片组件文件,所有可变内容通过 props 传入,组件内部不写死固定数据:
import React from 'react'; import { View, Text, Image, StyleSheet, TouchableOpacity } from 'react-native'; const Card = ({ item, onCardClick }) => { return ( <TouchableOpacity style={styles.cardWrapper} onPress={() => onCardClick?.(item)} activeOpacity={0.9} > <Image source={{ uri: item.coverImg }} style={styles.cover} /> <Text style={styles.title}>{item.title}</Text> <Text style={styles.desc} numberOfLines={2}>{item.description}</Text> {/* 可根据业务需求扩展其他字段、交互逻辑 */} </TouchableOpacity> ) } const styles = StyleSheet.create({ cardWrapper: { backgroundColor: '#fff', borderRadius: 12, padding: 14, marginBottom: 12, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3 }, cover: { width: '100%', height: 140, borderRadius: 8, marginBottom: 10 }, title: { fontSize: 17, fontWeight: '600', marginBottom: 6 }, desc: { fontSize: 14, color: '#666', lineHeight: 20 } }) export default Card;
2. 列表页调用卡片组件
长列表优先使用 FlatList 组件,自带内存回收、懒加载能力,性能优于普通遍历渲染:
import React from 'react'; import { View, FlatList, StyleSheet } from 'react-native'; import Card from './Card'; const CardListPage = () => { // 列表数据可从接口获取、本地配置,格式统一即可 const listData = [ { id: '1', coverImg: 'https://xxx.com/img1.jpg', title: '卡片1标题', description: '卡片1的说明内容' }, { id: '2', coverImg: 'https://xxx.com/img2.jpg', title: '卡片2标题', description: '卡片2的说明内容' }, // 更多卡片数据... ] const renderItem = ({ item }) => ( <Card item={item} onCardClick={(cardInfo) => console.log('点击了卡片', cardInfo)} /> ) return ( <View style={styles.pageContainer}> <FlatList data={listData} renderItem={renderItem} keyExtractor={item => item.id} contentContainerStyle={styles.listContent} /> </View> ) } const styles = StyleSheet.create({ pageContainer: { flex: 1, backgroundColor: '#f5f5f5' }, listContent: { padding: 16 } }) export default CardListPage;
补充说明
- 如果不同卡片存在布局差异,可以给卡片传入
type字段,在卡片组件内做分支渲染即可,不需要单独开发多个卡片组件 - 若列表数据量少于10条,也可以直接用
ScrollView+map遍历渲染卡片,写法更简单
内容的提问来源于stack exchange,提问作者Tech Sagan
相关产品推荐
相关产品推荐

