简体   繁体   English

'错误:未知命名模块',从动态路径加载react-native映像

[英]'Error: Unknown named module', loading react-native image from a dynamic path

When i use the Image component in React-native, it works fine when I declare my image's path/source as an inline string: 当我在React-native中使用Image组件时,当我将图像的路径/源声明为内联字符串时,它可以正常工作:

 <Image
    style={styles.img}
    source={require('mypic.png')}
 />

But when I define the path as a variable like this: 但是当我将路径定义为这样的变量时:

 var img = 'mypic.png';
 <Image
    style={styles.img}
    source={require(img)}
 />

...it doesn't work. ......它不起作用。 The error msg is "Error: unknown named module 'mypic.png'" 错误消息msg是“错误:未知命名模块'mypic.png'”

I have many images, and I need to require them dynamically. 我有很多图像,我需要动态地要求它们。 There are too many to write manual import statements to require them one-by-one. 编写手动导入语句有太多要求逐个使用它们。

Even with a simple toggle like this one, it's far less efficient: 即使使用像这样的简单切换,效率也会低得多:

var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');

How do people usually solve for dynamic loading of variable images? 人们通常如何解决变量图像的动态加载?

You cannot do dynamic static images, so you can either use uri or do static things like var test=require('image'). 你不能做动态静态图像,所以你可以使用uri或做静态的东西,如var test = require('image')。 Have a look at this issue: https://github.com/facebook/react-native/issues/2481 看看这个问题: https//github.com/facebook/react-native/issues/2481

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM