React Native自定义组件传相对路径图片require报错如何解决?
错误原因
React Native 中的 require 是在编译打包阶段静态执行的,不支持传入动态变量作为路径参数。你代码中 require(imageSrc) 里的 imageSrc 是运行时才确定的 prop,打包阶段无法识别,因此会抛出无效调用错误。
解决方案
方案1:调用组件时直接传入 require 后的图片资源(最推荐)
直接把图片资源的引用作为 prop 传入,不需要在自定义组件内部执行 require,完全符合 RN 的静态资源加载规则:
- 调整 GoalButton 组件代码:
const GoalButton = ({ buttonStyle, onPress, text, imageSrc, imageStyle, textStyle, }) => { return ( <TouchableOpacity onPress={onPress}> <View style={buttonStyle}> {/* 直接使用传入的imageSrc,不需要内部执行require */} <Image style={imageStyle} source={imageSrc} /> <Text style={textStyle}>{text}</Text> </View> </TouchableOpacity> ); }; GoalButton.defaultProps = { buttonStyle: styles.buttonStyle, onPress: () => null, imageStyle: styles.imageStyle, textStyle: styles.textStyle, }; export default GoalButton;
- 调整调用方式:
<GoalButton text={'Meal Plan'} imageSrc={require('../assets/images/plate.png')} />
方案2:必须传入路径字符串时,提前创建静态资源映射表
如果业务场景要求必须传入字符串路径,可以把所有用到的图片路径提前做静态映射,组件内部根据传入的路径字符串匹配对应的资源:
- 新建静态资源映射文件
imageMap.js:
// 提前注册所有需要用到的图片资源 export const imageMap = { "../assets/images/plate.png": require("../assets/images/plate.png"), "../assets/images/sport.png": require("../assets/images/sport.png"), // 其余用到的图片都按上述格式在此处注册 };
- 调整 GoalButton 组件代码:
import { imageMap } from './imageMap'; const GoalButton = ({ buttonStyle, onPress, text, imageSrc, imageStyle, textStyle, }) => { return ( <TouchableOpacity onPress={onPress}> <View style={buttonStyle}> <Image style={imageStyle} source={imageMap[imageSrc]} /> <Text style={textStyle}>{text}</Text> </View> </TouchableOpacity> ); };
调用方式可以和你原来的写法保持不变。
内容的提问来源于stack exchange,提问作者Uchechukwu Nwafor
相关产品推荐
相关产品推荐

