简体   繁体   English

在React Native中动态地需要图像

[英]Require Image dynamically in React Native

The documentation of React native (0.21) states, that it is only possible, to load pictures statically, ie if the file name is somehow known in advance: React native(0.21)的文档指出,只有静态加载图片,即文件名是否以某种方式预先知道:

Note that in order for this to work, the image name in require has to be known statically. 请注意,为了使其工作,必须静态地知道require中的图像名称。

Source: https://facebook.github.io/react-native/docs/images.html#content 资料来源: https//facebook.github.io/react-native/docs/images.html#content

An example is given: 给出了一个例子:

// GOOD
<Image source={require('./my-icon.png')} />

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />

Unfortunately, in my case, I do not know the file names of the pictures in advance, as they are configured in a JSON file. 不幸的是,在我的情况下,我不提前知道图片的文件名,因为它们是在JSON文件中配置的。

Is there a way to use local image files within react native? 有没有办法在本机中使用本地图像文件? I could load them via the file:// protocol, if I knew the location of the files? 我可以通过file://协议加载它们,如果我知道文件的位置? Is there a constant or variable for he location of the app within the iOS file system? iOS文件系统中应用程序的位置是否有常量或变量?

Yes, you can use images dynamically. 是的,您可以动态使用图像。 They're treated, however, as network images. 然而,它们被视为网络图像。 What this means is that the packager didn't attach any image metadata (width, height). 这意味着打包器没有附加任何图像元数据(宽度,高度)。

If you've a few images, simply leverage the packager. 如果您有一些图像,只需利用打包器即可。

// GOOD
var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');
<Image source={icon} />

The other option is to save metadata (width, height) in your JSON. 另一种选择是在JSON中保存元数据(宽度,高度)。 You'll need to specify at least the height for network images (or dynamic images). 您至少需要指定网络图像(或动态图像)的高度。 Given the metadata(width, height) and screen dimensions using ( React.Dimensions ), it's trivial to select appropriate height. 使用( React.Dimensions )给出元数据(宽度,高度)和屏幕尺寸,选择合适的高度是微不足道的。 Use react-native-orientation if your app needs to work in portrait and landscape mode. 如果您的应用需要在纵向和横向模式下工作,请使用react-native-orientation

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

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