在react native listview中添加动态本地图像

Adding dynamic local images in a react native listview

本文关键字:动态 地图 图像 添加 react native listview      更新时间:2023-09-26

我试图在一个简单的应用程序中加载一些本地图像,我正在使用react native。

我在这里遵循指南- https://facebook.github.io/react-native/docs/images.html

不幸的是,该指南说:

请注意,为了使其工作,必须静态地知道require中的图像名称。

这就是为什么我的代码不工作,当我试图呈现行在列表视图:

renderRow(chat){
  return (
      <View style={ styles.row }>
        <Image
          source={require(`../images/${chat.image}`)} //this is the part that's not working. It can't require a dynamic path
          style={ styles.cellImage }
          />
      </View>
);
}

我怎样才能做到这一点?或者你能建议另一种可行的方法吗?

这很奇怪,但如果您有一组图像选项(如果图像存在于项目中,这是有意义的),那么您可以根据给定条件返回静态所需的图像。

getSource() {
    if (condition) {
        return require( '../images/option-one' );
    } else {
        return require( '../images/default-option' );
    }
}
renderRow(chat){
    return (
        <View style={ styles.row }>
            <Image
                source={ this.getSource() }
                style={ styles.cellImage }
            />
        </View>
    );
}