React Native中点击Card跳转至对应页面的实现方法
React Native 卡片点击跳转实现方案
前提准备
确保你已经配置了React Navigation栈导航,且ScreenA、ScreenB、ScreenC、ScreenD这几个页面组件已在导航栈中完成注册。
修改Home.js代码
用Pressable包裹你的卡片组件,在onPress回调里通过switch语句根据卡片ID判断跳转目标:
import React from 'react'; import { View, Text, Pressable, StyleSheet } from 'react-native'; import CardStyle from './CardStyle'; const Home = ({ navigation }) => { // 你的卡片数据数组 const cardData = [ { id: 1, title: '卡片1' }, { id: 2, title: '卡片2' }, { id: 3, title: '卡片3' }, { id: 4, title: '卡片4' }, ]; const handleCardPress = (cardId) => { switch (cardId) { case 1: navigation.navigate('ScreenA'); break; case 2: navigation.navigate('ScreenB'); break; case 3: navigation.navigate('ScreenC'); break; case 4: navigation.navigate('ScreenD'); break; default: console.log('无效卡片ID'); } }; return ( <View style={styles.container}> <View style={styles.row}> {cardData.slice(0, 2).map(card => ( <Pressable key={card.id} style={CardStyle.cardContainer} onPress={() => handleCardPress(card.id)} > <Text style={CardStyle.cardTitle}>{card.title}</Text> {/* 插入你卡片内的其他内容 */} </Pressable> ))} </View> <View style={styles.row}> {cardData.slice(2, 4).map(card => ( <Pressable key={card.id} style={CardStyle.cardContainer} onPress={() => handleCardPress(card.id)} > <Text style={CardStyle.cardTitle}>{card.title}</Text> {/* 插入你卡片内的其他内容 */} </Pressable> ))} </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 16, }, row: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 16, }, }); export default Home;
关键说明
- Pressable组件:RN官方推荐的可点击容器,直接包裹卡片内容即可实现点击交互,替代旧的Touchable系列组件。
- handleCardPress函数:接收卡片ID,通过switch匹配不同ID,调用
navigation.navigate完成页面跳转。注意navigation是通过组件props传入的,需确保Home页面已在导航栈中注册。 - 布局逻辑:用slice方法把卡片数组拆分为两行,每行两个卡片,保留你原有的布局结构。
CardStyle.js 样式示例(无需修改)
假设你的样式文件如下,保持原有配置即可:
import { StyleSheet } from 'react-native'; const CardStyle = StyleSheet.create({ cardContainer: { width: '48%', backgroundColor: '#fff', borderRadius: 8, padding: 16, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3, }, cardTitle: { fontSize: 16, fontWeight: 'bold', }, }); export default CardStyle;
内容的提问来源于stack exchange,提问作者Freya23
相关产品推荐
相关产品推荐

