React Native:如何在用户输入后生成含输入内容的盒子并在其他页面展示?
React Native 实现输入数据传递与跨页面盒子展示
1. 提交时传递数据到目标页面
在 AddFood 组件的 showAlert 函数中,验证通过后将输入数据打包并通过导航传递到目标页面:
const showAlert = () => { if (selected && quantity && metric && day && month && year) { Alert.alert("Food entered successfully"); // 打包输入数据 const foodData = { name: selected, quantity: `${quantity} ${metric}`, useByDate: `${day}/${month}/${year}` }; // 导航到目标页面(替换为你的目标页面名称)并传递数据 props.navigation.navigate('FoodList', { foodItem: foodData }); } else { Alert.alert("Please fill in all the fields"); } }
2. 创建可复用的食品信息盒子组件
新建一个独立组件用于渲染食品信息盒子,可在任何页面复用:
import { View, Text, StyleSheet } from 'react-native'; const FoodItemBox = ({ food }) => { return ( <View style={styles.foodBox}> <Text style={styles.foodName}>{food.name}</Text> <Text style={styles.foodDetail}>Quantity: {food.quantity}</Text> <Text style={styles.foodDetail}>Use by: {food.useByDate}</Text> </View> ); }; const styles = StyleSheet.create({ foodBox: { backgroundColor: '#f8f8f8', padding: 18, borderRadius: 10, marginVertical: 10, borderWidth: 1, borderColor: '#e0e0e0', shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3 }, foodName: { fontSize: 19, fontWeight: '600', marginBottom: 8 }, foodDetail: { fontSize: 14, color: '#555', marginVertical: 2 } }); export default FoodItemBox;
3. 在目标页面接收并渲染盒子
在导航栈的目标页面(例如 FoodList)中,接收传递的数据并使用 FoodItemBox 组件渲染:
import { View, Text, StyleSheet } from 'react-native'; import FoodItemBox from './FoodItemBox'; // 替换为你的组件路径 const FoodListScreen = ({ route }) => { // 从路由参数中获取传递的食品数据 const { foodItem } = route.params; return ( <View style={styles.container}> <Text style={styles.title}>Added Food Item</Text> <FoodItemBox food={foodItem} /> {/* 如果需要展示多个条目,可以用 useState 维护列表并循环渲染 */} {/* 例如:{foodList.map(item => <FoodItemBox key={item.name} food={item} />)} */} </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 20, backgroundColor: '#fff' }, title: { fontSize: 22, fontWeight: 'bold', marginBottom: 20 } }); export default FoodListScreen;
补充说明
- 不需要在目标页面初始化
AddFood组件,通过导航参数传递数据是更合理的方式 - 如果需要支持添加多个食品条目,可以在目标页面使用
useState维护一个食品列表数组,每次新数据传入时追加到数组中
内容的提问来源于stack exchange,提问作者Hercules' Creed
相关产品推荐
相关产品推荐

