React Native:require()with Dynamic String? [英] React Native: require() with Dynamic String?

查看:119
本文介绍了React Native:require()with Dynamic String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试要求动态资源时,我已经阅读了几篇关于人们使用React Native和 require()函数的帖子,如下所示:

I have read several posts about issues that people are having with React Native and the require() function when trying to require a dynamic resource such as:

动态(失败)

urlName = "sampleData.json";
data = require('../' + urlName);

vs。静态(成功)

data = require('../sampleData.json');

我已经读过一些线程,这是React Native中的一个错误,而在其他线程中,这是一个错误功能。

I have read on some threads that this is a bug in React Native and in others that this is a feature.

是否有新方法需要函数内的动态资源?

Is there a new way to require a dynamic resource within a function?

相关帖子(全部在React时间相当旧):

Related Posts (all fairly old in React time):

  • Importing Text from local json file in React native
  • React Native - Dynamically List/Require Files In Directory
  • React Native - Image Require Module using Dynamic Names
  • React Native: how to use require(path) with dynamic urls?

推荐答案

正如我所听到的那样,react的 require()只使用静态url而不是变量,这意味着你必须要做 require('/ path / file'),请查看 github上的问题这一个以获得更多替代解决方案,还有其他几种方法可以做它!
例如

As i have heard of, react's require() only uses static url not variables, that means that you have to do require('/path/file'), take a look at this issue on github and this one for more alternative solutions, there are a couple of other ways to do it! for e.g

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

export default images;

然后

import Images from './img/index';

render() {
    <Image source={Images.profile.comments} />
}

来自回答

这篇关于React Native:require()with Dynamic String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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