React Native复制应用assets文件到iOS/Android设备报错求助
React Native 复制Assets文件到设备存储的解决方案
问题原因
RNFS 的 copyFile 方法无法直接识别 assets/xxx 这类相对路径——iOS 和 Android 对应用内 assets 文件的存储机制不同,需要针对平台使用专门的 assets 复制方法。
修正后的代码
import { Platform } from 'react-native'; import RNFS from 'react-native-fs'; const copyAssetToDevice = async () => { const assetPath = 'assets/icons/bootsplash.png'; const destinationPath = `${RNFS.DocumentDirectoryPath}/bootsplash.png`; try { if (Platform.OS === 'ios') { // iOS 需去掉路径前缀的 "assets/",直接传入 assets 目录内的相对路径 await RNFS.copyAssetsFileIOS('icons/bootsplash.png', destinationPath, 0, 0); } else { // Android 直接使用完整的 assets 相对路径 await RNFS.copyFileAssets(assetPath, destinationPath); } console.log('文件复制成功,路径:', destinationPath); } catch (error) { console.error('复制失败:', error); } }; // 调用执行 copyAssetToDevice();
关键注意事项
- 确认 assets 目录结构:确保项目中确实存在
assets/icons/bootsplash.png文件,并且在metro.config.js中正确配置 assets 路径:const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); module.exports = mergeConfig(getDefaultConfig(__dirname), { resolver: { assetExts: ['png', 'jpg', 'jpeg'], // 包含你的文件扩展名 }, assets: ['./assets/'], // 注册 assets 目录 }); - iOS 额外配置:在 Xcode 中确认 assets 文件夹已添加到项目,且文件的「Target Membership」已勾选对应主 target。
- Android 额外配置:确保文件放置在
android/app/src/main/assets目录下,Gradle 会自动打包该目录内的文件。
内容的提问来源于stack exchange,提问作者civani mahida
相关产品推荐
相关产品推荐

