首页 > 解决方案 > 如何将不同的图像作为背景上传到平面列表中的卡片视图

问题描述

再会!我正在使用 API 调用来获取项目详细信息。从 API 我只会得到项目 ID、项目名称、项目描述。我想为卡片中的平面列表视图提供不同的图像作为背景。截至目前,我从 API 获得了 10 个项目。我的项目文件夹中有十张图像。我以数组格式存储并导入到我的主要组件中。但我无法将不同的图像作为背景。任何人都可以帮助你实现这一目标。提前致谢。

//Code to get the images

renderImage = ({ item }) => (
    <View>
      <ImageBackground source={CardImages[item]} />
    </View>
  );


//Main Component: 

<FlatList
                numColumns={numColumns}
                data={data}
                renderItem={({ item, index }) => 
                  return (
                    <Card
                      onPress={() =>
                        this.props.navigation.push("ItemDet", {
                          data: item,
                        })
                      }
                      style={{
                        margin: 8,
                        borderRadius: 16,
                        width: config.deviceWidth * 0.43,
                        height: config.deviceWidth * 0.54,
                        overflow: "hidden",
                        justifyContent: "space-evenly",
                        marginLeft: 14,
                      }}
                    >
                      <ImageBackground
                        style={{
                          height: config.deviceWidth * 0.54,
                          width: config.deviceWidth * 0.43,
                          resizeMode: "cover",
                        }}
                      renderImage={this.renderImage}//here is the call for dynamic image background
                      >
                      </ImageBackground>
                      </Card>
                      />

标签: reactjsreact-native

解决方案


你的代码很奇怪,所以我决定用我的方式修复它的语法,希望你能在这里找到一些有用的东西。

const CardImages = {
    firstImage: require('./your-first-image.png'),
    secondImage: require('./your-second-image.png'),
    thirdImage: require('./your-third-image.png'),
  };

  return (
    <FlatList
      numColumns={numColumns}
      data={data}
      renderItem={({ item, index }) => {
        return (
          <Card
            onPress={() =>
              this.props.navigation.push('ItemDet', {
                data: item,
              })
            }
            style={{
              margin: 8,
              borderRadius: 16,
              width: config.deviceWidth * 0.43,
              height: config.deviceWidth * 0.54,
              overflow: 'hidden',
              justifyContent: 'space-evenly',
              marginLeft: 14,
            }}>
            <ImageBackground
              style={{
                height: config.deviceWidth * 0.54,
                width: config.deviceWidth * 0.43,
                resizeMode: 'cover',
              }}
              source={CardImages[item]}
            />
          </Card>
        );
      }}
    />
  );

推荐阅读