React Native:require()with Dynamic String? [英] 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):
- 从React native中的本地json文件导入文本
- React Native - 在目录中动态列出/需要文件
- React Native - 使用动态名称的图像需要模块
- React Native:如何使用req uir(path)with dynamic urls?
- 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屋!