React-Router-Native传递图片参数的问题及解决方案咨询
React Router Native + TypeScript 传递图片资源到其他页面的解决方案
首先纠正你代码里的几个小问题:
- 路由路径
Page2/:icon是路径参数写法,但你实际是通过location.state传递,这个路径参数完全多余,删掉即可。 - React Native组件名和属性是驼峰命名:
touchableOpacitiy→TouchableOpacity,onpress→onPress。
核心问题:TypeScript 类型缺失
useLocation()返回的state默认类型是unknown,直接赋值给Image的source会触发类型错误。解决思路是给路由状态定义明确的类型,再通过类型断言让TypeScript识别。
步骤1:定义路由状态类型
可以单独创建类型文件(比如src/types/router.ts),或者直接在组件内定义:
import { ImageSourcePropType } from 'react-native'; export type Page2RouteState = { icon: ImageSourcePropType; };
步骤2:Page1 正确传递图片
import的本地图片在React Native中会被编译为符合ImageSourcePropType的对象,直接通过state传递即可:
import { TouchableOpacity, View, Image } from 'react-native'; import { useNavigate } from 'react-router-native'; import Icon from '../image/icon.png'; import { Page2RouteState } from '../types/router'; // 导入类型 const Page1 = () => { const navigate = useNavigate(); const handleGoToPage2 = () => { navigate('Page2', { state: { icon: Icon } as Page2RouteState }); }; return ( <View> <TouchableOpacity onPress={handleGoToPage2}> <Image source={Icon} style={{ width: 50, height: 50 }} /> </TouchableOpacity> </View> ); }; export default Page1;
步骤3:Page2 接收并使用图片
通过类型断言明确location.state的类型,即可正常使用:
import { View, Image } from 'react-native'; import { useLocation } from 'react-router-native'; import { Page2RouteState } from '../types/router'; const Page2 = () => { const location = useLocation(); // 用类型断言告诉TypeScript state的结构 const { icon } = location.state as Page2RouteState; return ( <View> <Image source={icon} style={{ width: 100, height: 100 }} /> </View> ); }; export default Page2;
额外说明
- 如果是远程图片(URL字符串),传递字符串即可,
ImageSourcePropType兼容字符串和本地资源对象。 - 不要用路径参数传递图片资源:路径参数适合传递简单的字符串/数字,图片资源是对象,不适合放在URL中。
内容的提问来源于stack exchange,提问作者Mer Merced
相关产品推荐
相关产品推荐

