安装react-native-fs
npm
npm install react-native-fs --save
yarn
yarn add react-native-fs
安卓配置
android/settings.gradle
...
include ':react-native-fs'
project(':react-native-fs').projectDir = new File(settingsDir, '../node_modules/react-native-fs/android')
android/app/build.gradle
...
dependencies {
...
implementation project(':react-native-fs')
}
android\app\src\main\java\com\reactnative_demo\MainApplication.kt
把原代码
import com.rnfs.RNFSPackage; // 导入模块
// 下面这段代码要改
override fun getPackages(): List<ReactPackage> {
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return PackageList(this).packages
}
改为
import com.rnfs.RNFSPackage; // 导入模块
// 改成这样
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
add(RNFSPackage()) // 如果报错提示覆盖注册(已经自动注册了),那么把这行注释掉即可
}
使用
import {StyleSheet, Text, View, Button} from 'react-native';
import React from 'react';
import RNFS from 'react-native-fs';
export default function CsvFile() {
const handleClick = () => {
const path = RNFS.ExternalStorageDirectoryPath + '/test.txt';
RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
.then(success => {
console.log('FILE WRITTEN! --> ', path);
})
.catch(err => {
console.log(err.message);
});
};
return (
<View>
<Button title="写入文件" onPress={() => handleClick()} />
</View>
);
}
const styles = StyleSheet.create({});
关于存储路径
RNFS.MainBundlePath (String) 主包目录的绝对路径(在 Android 上不可用)
RNFS.CachesDirectoryPath (String) 缓存目录的绝对路径
RNFS.ExternalCachesDirectoryPath (String) 外部缓存目录的绝对路径(仅限安卓)
RNFS.DocumentDirectoryPath (String) 文档目录的绝对路径
RNFS.DownloadDirectoryPath (String) 下载目录的绝对路径(仅在 android 上)
RNFS.TemporaryDirectoryPath (String) 临时目录的绝对路径(在 Android 上回退到 Caching-Directory)
RNFS.LibraryDirectoryPath (String) NSLibraryDirectory 的绝对路径(仅限 iOS)
RNFS.ExternalDirectoryPath (String) 外部文件的绝对路径,共享目录(仅限安卓)
RNFS.ExternalStorageDirectoryPath (String) 外部存储的绝对路径,共享目录(仅限安卓)
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/275277.html