You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Expo如何读取txt文件并在页面展示文本内容

Expo环境读取TXT文件并展示内容实现方案

Expo环境不需要退出托管工作流做原生开发,使用官方维护的文件系统相关依赖即可实现TXT读取,以下是两种高频场景的可直接复用的实现代码:

前置依赖安装

先安装三个官方维护的依赖,不需要额外原生配置:
npx expo install expo-file-system expo-document-picker expo-asset


场景1:读取项目内置打包的TXT文件

适用于TXT文件存放在项目代码目录中、跟随安装包一起打包发布的情况,比如内置的协议文本、说明文档等。

  • 首先在项目根目录的app.json中添加资源打包配置,避免构建时TXT文件被过滤:
{
  "expo": {
    "assetBundlePatterns": [
      "**/*",
      "*.txt"
    ]
  }
}
  • 页面实现代码:
import { useEffect, useState } from 'react';
import { Text, View, ScrollView } from 'react-native';
import * as FileSystem from 'expo-file-system';
import { Asset } from 'expo-asset';

export default function BuiltInTxtPage() {
  const [content, setContent] = useState('');

  useEffect(() => {
    const loadTxt = async () => {
      // 替换为你项目中TXT文件的实际相对路径
      const txtAsset = Asset.fromModule(require('./assets/agreement.txt'));
      await txtAsset.downloadAsync();
      // 指定UTF8编码读取,避免中文乱码
      const txt = await FileSystem.readAsStringAsync(txtAsset.uri, {
        encoding: FileSystem.EncodingType.UTF8
      });
      setContent(txt);
    };
    loadTxt();
  }, []);

  return (
    <ScrollView contentContainerStyle={{ padding: 20 }}>
      <Text style={{ lineHeight: 24 }}>{content}</Text>
    </ScrollView>
  );
}

场景2:读取用户设备本地存储的TXT文件

适用于需要让用户选择自己手机里存储的TXT文件、读取后展示内容的场景。
实现代码:

import { useState } from 'react';
import { Text, View, ScrollView, Button, Alert } from 'react-native';
import * as FileSystem from 'expo-file-system';
import * as DocumentPicker from 'expo-document-picker';

export default function LocalDeviceTxtPage() {
  const [content, setContent] = useState('');

  const handlePickTxt = async () => {
    try {
      const pickResult = await DocumentPicker.getDocumentAsync({
        type: 'text/plain', // 限制仅选择TXT格式文件
        copyToCacheDirectory: true
      });
      // 用户取消选择时直接中断流程
      if (pickResult.canceled) return;

      const fileUri = pickResult.assets[0].uri;
      const txt = await FileSystem.readAsStringAsync(fileUri, {
        encoding: FileSystem.EncodingType.UTF8
      });
      setContent(txt);
    } catch (err) {
      Alert.alert('读取失败', '无法读取选中的TXT文件,请检查文件是否损坏');
      console.error(err);
    }
  };

  return (
    <View style={{ flex: 1, padding: 20 }}>
      <Button title="选择手机中的TXT文件" onPress={handlePickTxt} />
      <ScrollView style={{ marginTop: 20 }}>
        <Text style={{ lineHeight: 24 }}>{content}</Text>
      </ScrollView>
    </View>
  );
}

踩坑提示

  • 中文乱码问题:如果读取后出现乱码,一般是TXT文件本身为GBK/GB2312编码,上述代码默认按UTF8解码,需要额外引入编码转换库对读取到的内容做转码处理即可。
  • 生产环境读不到内置TXT:优先检查app.json的资源打包配置,确认TXT文件路径在require引入时没有写错,开发环境可读取但生产环境读取失败基本都是TXT未被打进安装包导致。
  • 权限说明:上述实现不需要额外申请安卓/iOS的存储权限,Expo官方的文档选择器和文件系统接口读取用户主动选中的文件、应用缓存目录文件均不需要额外权限配置,上架应用商店不会出现权限合规问题。

内容的提问来源于stack exchange,提问作者omeletteEgg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 03:09:37