简体   繁体   中英

Displaying multiple images using FlatList component in react native

Am trying to display multiple images using the Flatlist component in react native but i get a TransformError for some reason, i also want each of the images that get displayed to have a diffrent background color that i set. here is the code i used

import React, { useState } from "react";
import { StyleSheet, Text, View, Image, FlatList } from "react-native";

export default function App() {
  const [category, setCategory] = useState([
    { name: "creative", id: "1" },
    { name: "traveling", id: "2" },
    { name: "cycling", id: "3" },
    { name: "business", id: "4" },
  ]);
  return (
    <View style={styles.container}>
      <FlatList
        keyExtractor={(item) => item.id}
        data={category}
        renderItem={({ item }) => (
          <Image source={require(`../../assets/images/${item.name}.png`)} />
        )}
      />
    </View>
  );
}

the images files in the assets folder are named exactly the same as the names in item.name

You cannot use require with dynamic params, you should make the require in category const.

const [category, setCategory] = useState([
    { name: "creative", id: "1", source: require('../../assets/images/creative.png') },
    { name: "traveling", id: "2", source: require('../../assets/images/traveling.png') },
  // and so on...
  ]);

// in FlatList

<FlatList
        keyExtractor={(item) => item.id}
        data={category}
        renderItem={({ item }) => (
          <Image source={item.source} />
        )}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM