React Native新手求助:如何在页面间传递并接收数据?
在React Native的ProductDetail页面接收传递的数据
嘿,刚接触React Native的时候,页面间传值确实容易懵,我来一步步帮你解决这个问题!
首先看你在ProductListing里的跳转代码,已经把item数据通过data: item传递给了ProductDetail页面,接下来分两种常见的导航库情况,告诉你怎么拿到这个数据:
情况1:使用Wix的react-native-navigation库
这种情况下,你传递的data会直接作为props传入ProductDetail组件,直接用this.props.data就能拿到:
import React, { Component } from 'react'; import { View, Text, Image } from 'react-native'; class ProductDetail extends Component { componentDidMount() { // 在这里可以拿到传递过来的商品数据 const product = this.props.data; console.log('当前商品信息:', product); } render() { const product = this.props.data; return ( <View style={{ padding: 20 }}> <Text style={{ fontSize: 20, fontWeight: 'bold' }}>{product.name}</Text> <Text style={{ fontSize: 16, color: '#666', marginTop: 8 }}>{product.type}</Text> <Image source={{ uri: product.image }} style={{ width: 200, height: 200, marginTop: 16, borderRadius: 8 }} /> </View> ); } } export default ProductDetail;
情况2:使用React Navigation(v4及更早版本)
如果用的是React Navigation的栈导航,你需要从navigation.state.params里取数据。另外建议你把跳转代码里的参数统一放到params字段里(当然如果你的现有写法能生效也可以直接取):
先调整ProductListing里的跳转方法(可选,但更规范)
pushProductDetailScreen(item){ this.props.navigation.push('ProductDetail', { title: item.name, subtitle: item.type, backButtonTitle: '', data: item }); };
然后在ProductDetail页面获取数据
import React, { Component } from 'react'; import { View, Text, Image } from 'react-native'; class ProductDetail extends Component { componentDidMount() { const product = this.props.navigation.state.params.data; console.log('当前商品信息:', product); } render() { const product = this.props.navigation.state.params.data; return ( <View style={{ padding: 20 }}> <Text style={{ fontSize: 20, fontWeight: 'bold' }}>{product.name}</Text> <Text style={{ fontSize: 16, color: '#666', marginTop: 8 }}>{product.type}</Text> <Image source={{ uri: product.image }} style={{ width: 200, height: 200, marginTop: 16, borderRadius: 8 }} /> </View> ); } } export default ProductDetail;
如果你用的是React Navigation v5+(函数组件写法)
现在很多新项目用的是函数组件+hooks,这种情况下用useRoute钩子就能拿到参数:
import React from 'react'; import { View, Text, Image } from 'react-native'; import { useRoute } from '@react-navigation/native'; function ProductDetail() { const route = useRoute(); // 从route.params里取出传递的商品数据 const product = route.params.data; return ( <View style={{ padding: 20 }}> <Text style={{ fontSize: 20, fontWeight: 'bold' }}>{product.name}</Text> <Text style={{ fontSize: 16, color: '#666', marginTop: 8 }}>{product.type}</Text> <Image source={{ uri: product.image }} style={{ width: 200, height: 200, marginTop: 16, borderRadius: 8 }} /> </View> ); } export default ProductDetail;
小提示
- 如果拿到的数据是
undefined,可以在ProductDetail的componentDidMount里打印console.log(this.props)(类组件)或者console.log(route.params)(函数组件),看看数据到底存在哪个字段里,可能和你的导航库版本有关 - 确保你已经在导航配置里正确注册了
ProductDetail页面,不然跳转的时候会报错
内容的提问来源于stack exchange,提问作者Huby03
相关产品推荐
相关产品推荐

