React Native:require() 与动态字符串? [英] React Native: require() with Dynamic String?

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

问题描述

我已经阅读了几篇关于人们在尝试请求动态资源时遇到的问题的文章,其中包括 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 的 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() 与动态字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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