react native:导入具有动态文件名的文件

问题描述 投票:1回答:1

在React Native中:我想在运行时使用require导入文件。例如let mydata = require('../data/' + new Date().getFullYear().toString() + '.json');

由于我有多个数百个json文件,因此很难对所有文件进行硬编码。在角度,您可以只使用上面的代码,它可以工作,但我认为RN需要静态路径。我希望有另一种方法可以做到这一点。任何帮助表示赞赏!

json react-native dynamic import require
1个回答
1
投票

这是我遇到的问题之一。如我所知,react的require()仅使用静态url而不是变量,这意味着您必须执行require('/path/file')。这是我的解决方案版本:

const images = {
    profile: {
        profile: require('./profile/profile.png'),
        comments: require('./profile/comments.png'),
    },
    image1: require('./image1.jpg'),
    image2: require('./image2.jpg'),
};
export default images;

不是最佳选择,但是有时您可以摆脱它。

© www.soinside.com 2019 - 2024. All rights reserved.