如何在 React Native 中存储和导入静态文件?

问题描述:

我想将静态 *.txt、*.svg 甚至 *.js 文件存储在 assets 文件夹(或其他常用的首选路径).然后我想将它们作为字符串导入 App.js.关于这个话题有很多相互矛盾的信息.如何在全新的应用中正确执行此操作?

I would like to store static *.txt, *.svg, and even *.js files in a React Native project (clean, without any Expo and other wrappers, Webpacks, using Babel only) in assets folder (or other commonly preferred path). Then I would like to import them into the App.js as strings. There is so much contradictory info on the topic. How do I properly do that in a brand new app?

如果你有一个像这样的 json 文件:

If you have a json file like:

const data = {
  key1: 'value1',
  key2: 'value2',
};

export default data;

访问您的数据的唯一方法是通过:

The only way to access your data is through:

import data from '../your/relative/path/to/data';

如果您想在该文件中导入特定的密钥,那么您的 json 文件将是这样的:

If you want to import specific key in that file, then your json file would be somthing like that:

export const key1 = 'value1';
export const key2 = 'value2';

const data = {
    key1,
    key2,
};

export default data;

现在你有能力做到这一点:

Now you'd have the ability to do that:

import { key1 } from '../your/relative/path/to/data';

import data from '../your/relative/path/to/data';

我建议对于 text 文件,将它们存储在 constants 文件夹中,并为每个类别制作一个相关的 .js 文件:

I suggest for text files, you store them in a constants folder, and make a a relevant .js file for each category:

constants.js 文件:

constants.js file:

export const CONST_KEY_1 = 'some value';
export const CONST_KEY_2 = 'some other value';
export default {
    CONST_KEY_1,
    CONST_KEY_2
};

对于 svg 文件:

快速方法:将每个文件的 file_uri 存储在一个键值对中,就像我们在 constants.js 文件中所做的那样

Fast approach: to store the file_uri of each file in a key value pair in the same way we did in the constants.js file

更好的方法:以与在 constants.js 文件中相同的形式存储这些 svg 文件的 svg 路径 ...并使用 react-native-svg npm 模块呈现这些文件.

Better approach: to store svg path of these svg files in the same form we did in the constants.js file ... and render these files using react-native-svg npm module.