安装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
把原代码文章来源:https://www.toymoban.com/news/detail-844264.html
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
}
改为文章来源地址https://www.toymoban.com/news/detail-844264.html
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) 外部存储的绝对路径,共享目录(仅限安卓)
到了这里,关于react native 0.73 配置 react-native-fs的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!