首页 文章

React Native - 使用动态名称的图像需求模块

提问于
浏览
39

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

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

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

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

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

我收到错误:

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

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

React native error with dynamic image name

6 回答

  • 29

    这在“Static Resources”部分的文档中有所介绍:

    引用捆绑中图像的唯一允许方法是在源中逐字写入require('image!of the-asset') .

    // 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} />
    

    但是,您还需要记住将您的图像添加到Xcode中的应用程序中的xcassets捆绑包中,尽管从您的评论中可以看出您已经完成了 .

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

  • 1

    这对我有用:

    我制作了一个自定义图像组件,它接受一个布尔值来检查图像是来自网络还是从本地文件夹传递 .

    // In index.ios.js after importing the component
    <CustomImage fromWeb={false} imageName={require('./images/logo.png')}/>
    
    // In CustomImage.js which is my image component
    <Image style={styles.image} source={this.props.imageName} />
    

    如果您看到代码,而不是使用其中一个:

    // NOTE: Neither of these will work
    source={require('../images/'+imageName)} 
    var imageName = require('../images/'+imageName)
    

    相反,我只是将整个 require('./images/logo.png') 作为道具发送 . It works!

  • -1

    RELEVANT IF YOU HAVE KNOWN IMAGES (URLS):

    我通过这个问题破解了我的方式:

    我创建了一个文件,其中包含一个存储图像和图像名称的对象:

    const images = {
      dog: {
        imgName: 'Dog', 
        uri: require('path/to/local/image')
      },
      cat: {
        imgName: 'Cat on a Boat', 
        uri: require('path/to/local/image')
      }
    }
    
    export { images };
    

    然后我将对象导入到我想要使用它的组件中,并像我这样进行条件渲染:

    import { images } from 'relative/path';
    
    if (cond === 'cat') {
      let imgSource = images.cat.uri;
    }
    
    <Image source={imgSource} />
    

    我知道这不是最有效的方式,但绝对是一种解决方法 .

    希望能帮助到你!

  • 4

    您可以使用

    <Image source={{uri: 'imagename'}} style={{width: 40, height: 40}} />
    

    显示图像 .

    从:

    https://facebook.github.io/react-native/docs/images.html#images-from-hybrid-app-s-resources

  • 33

    我知道这已经过时了,但是我会在这里添加这个,因为我找到了这个问题,同时寻找解决方案 . 文档允许使用uri:'网络图像'

    https://facebook.github.io/react-native/docs/images#network-images

    对我来说,我得到了动态的图像

    <Image source={{uri: image}} />
    
  • 18

    你应该使用一个对象 .

    例如,让's say that I' ve向API发出一个AJAX请求,它返回一个我保存为 imageLink 状态的图像链接:

    source={{uri: this.state.imageLink}}

相关问题