动态添加本地存储的图像到列表视图 [英] Dynamically add locally stored images to list view

查看:45
本文介绍了动态添加本地存储的图像到列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将本地存储的图像渲染到 ListView 中.由于应用程序的打包方式,我似乎无法使用 source={require( category.image )} .使用 source={{uri: category.image}} 不会使我的应用程序崩溃,也不会加载图像.这是我的 React Native 类:

I would like to render locally stored images into a ListView. It seems I cannot use source={require( category.image )} due to the way the app is packaged. Using source={{uri: category.image}} does not crash my app but also doesn't load the image. Here is my React Native class:

var Categories = React.createClass({

  getInitialState: function() {

    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      dataSource: ds.cloneWithRows([
        {'name':'Test', 'image':'./images/categories/test.jpg'},
{'name':'Test', 'image':'./images/categories/test.jpg'},
{'name':'Test', 'image':'./images/categories/test.jpg'},
{'name':'Test', 'image':'./images/categories/test.jpg'},
{'name':'Test', 'image':'./images/categories/test.jpg'},
{'name':'Test', 'image':'./images/categories/test.jpg'},
{'name':'Test', 'image':'./images/categories/test.jpg'},
{'name':'Test', 'image':'./images/categories/test.jpg'},
{'name':'Test', 'image':'./images/categories/test.jpg'},
{'name':'Test', 'image':'./images/categories/test.jpg'},
      ]),
    };
  },

  renderCategory: function(category) {

    return (

      <View style={styles.container}>
        <Image source={{uri: category.image}}>

          <View style={styles.backdropView}>
            <Text style={styles.headline}>
              {category.name}
            </Text>
          </View>

        </Image>
      </View>
    );
  },

  render: function() {

    return (

      <ListView
        dataSource={this.state.dataSource}
        renderRow={this.renderCategory} />
    );
  },
});

如何在不进行硬编码的情况下将图像添加到页面中?

How can I add the images to the page without hard coding them?

推荐答案

React Native 打包程序将预处理您的代码并查找指向图像的 require 语句并将这些语句与您的应用程序捆绑在一起.由于这是在编译时而不是运行时完成的,因此您不能动态地要求它们.

The React Native packager will preprocess your code and look for require statements that points to images and bundle those with your app. Since this is done at compile time and not run time you cannot dynamically require them.

如果你必须这样做,那么我建议使用远程图像或将它们添加到 Images.xcassets 并使用 {uri: 'asset_name'} 代替.另一种方法是在启动时使用一堆 require 创建一个数组或对象,然后动态使用该内容.

If you must do that, then I'd suggest using remote images or adding them to Images.xcassets and using {uri: 'asset_name'} instead. Another approach would be to create an array or object at startup with a bunch of require's and then use that content dynamically.

这篇关于动态添加本地存储的图像到列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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