React Native - 使用动态名称的图像需要模块 [英] React Native - Image Require Module using Dynamic Names

查看:30
本文介绍了React Native - 使用动态名称的图像需要模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 React Native 构建一个测试应用程序.到目前为止,Image 模块运行良好.

例如,如果我有一个名为 avatar 的图像,下面的代码片段就可以正常工作.

但是如果我将其更改为动态字符串,我会得到

我收到错误:

<前>需要未知模块image!avatar".如果您确定模块在那里,请尝试重新启动打包程序.

显然,这是一个人为的例子,但动态图像名称很重要.React Native 不支持动态图片名称吗?

解决方案

这在静态资源":

<块引用>

在包中引用图像的唯一允许方式是在源代码中逐字写入 require('image!name-of-the-asset').

//好<图片来源={require('image!my-icon')}/>//坏的var icon = this.props.active ?'my-icon-active' : 'my-icon-inactive';<图片来源={require('image!' + icon)}/>//好的var icon = this.props.active ?require('image!my-icon-active') : require('image!my-icon-inactive');<图片来源={icon}/>

但是,您还需要记住在 Xcode 中将图像添加到应用程序中的 xcassets 包中,尽管从您的评论看来您已经这样做了.

http://facebook.github.io/react-native/docs/image.html#adding-static-resources-to-your-app-using-images-xcassets

I'm currently building a test app using React Native. The Image module thus far has been working fine.

For example, if I had an image named avatar, the below code snippet works fine.

<Image source={require('image!avatar')} />

But if I change it to a dynamic string, I get

<Image source={require('image!' + 'avatar')} />

I get the error:

Requiring unknown module "image!avatar". If you are sure the module is there, try restarting the packager.

Obviously, this is a contrived example, but dynamic image names are important. Does React Native not support dynamic image names?

解决方案

This is covered in the documentation under the section "Static Resources":

The only allowed way to refer to an image in the bundle is to literally write require('image!name-of-the-asset') in the source.

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

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

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

However you also need to remember to add your images to an xcassets bundle in your app in Xcode, though it seems from your comment you've done that already.

http://facebook.github.io/react-native/docs/image.html#adding-static-resources-to-your-app-using-images-xcassets

这篇关于React Native - 使用动态名称的图像需要模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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