在React Native中,您如何捆绑文本文件并在运行时读取其值? [英] In React Native how do you bundle a text file and read it's value at runtime?

查看:103
本文介绍了在React Native中,您如何捆绑文本文件并在运行时读取其值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能要这样做的一些原因:

A few reasons why I might do this:

  • 创建一些Web视图并注入从文件加载的javascript
  • 将大块文本分成单独的文件,而不是将其强制进入视图
  • 包括要在应用程序中使用的任意格式的原始数据(例如CSV)

在React Native中,您可以使用 require 导入图像文件,但是据我所知,这仅适用于图像文件.而且(奇怪地)它也适用于JSON文件(请参见导入文本来自React native中的本地json文件).但是,我从未见过任何有关导入纯旧文本文件的讨论.

In React Native you can use require to import an image file, but as far as I've seen, this only works for image files. And it (strangely) also works for JSON files (see Importing Text from local json file in React native). However, I haven't seen anywhere talking about importing plain old text files.

推荐答案

四处询问后,我能想到的最好方法是使用 react-native-fs 库来访问android资产".该派生请求是一个拉出请求,一旦合并,就可以使用它.

After looking and asking around, the best I can come up with is to use a fork of the react-native-fs library to access android "assets". This fork is a pull request out and as soon as it gets merged you can use it.

请注意,在android dev中,资产"专门指访问文件的原始内容.为了在react native方面执行此类操作,您需要编写一个native模块以与react接口,因此需要上面的库.请参见此处(并搜索资产).

Note that in android dev, "assets" specifically refer to accessing the raw contents of a file. In order to do this sort of thing on the react native side, you need to write a native module to interface with react, hence the library above. See here (and search for assets).

在您的本机反应项目中,创建一个名为 android/app/src/main/assets/text.txt 之类的文件.使用上述 react-native-fs 的版本,您可以执行:

In your react native project, make a file called something like android/app/src/main/assets/text.txt. Using the version of react-native-fs mentioned above, you do:

RNFS.readFileAssets('test.txt').then((res) => {
  console.log('read file res: ', res);
})

更新:如果您希望拉请求可以启用此功能具备的能力,您应该通过在GitHub上点赞让作者知道您想要的东西.

update: If you want the pull request that would enable this ability to go through, you should go let the author know you want it by giving it a thumbs up on github.

这篇关于在React Native中,您如何捆绑文本文件并在运行时读取其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆