【问题标题】:react native: importing a file with dynamic filename反应原生:导入具有动态文件名的文件
【发布时间】:2020-03-27 08:11:47
【问题描述】:

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

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

【问题讨论】:

    标签: json react-native dynamic import require


    【解决方案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;
    

    不是最好的选择,但有时你可以侥幸逃脱。

    【讨论】:

    • 谢谢,但那个解决方案对我不起作用,因为我有数百个文件,无法将所有文件硬编码到单独的 require 语句中
    猜你喜欢
    • 2020-06-19
    • 2021-02-18
    • 2022-08-22
    • 2015-10-06
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多