问题描述
我已经阅读了几篇关于人们在尝试请求动态资源时遇到的问题的文章,其中包括 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);
对比静态(成功):
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:如何使用 require(path) 与动态网址?
推荐答案
据我所知,react 的 require()
只使用静态 url 而不是变量,这意味着你必须做 require('/path/file')
,看看这个github 上的问题 和 this one 以获取更多替代解决方案,还有其他几种方法可以做到!例如
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() 与动态字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!