首页 > 解决方案 > 使用函数多次生成示例组件 React Native

问题描述

我是本机反应的新手,并尝试使用一个函数在 for 循环中多次创建相同的组件(如果可能的话)。下面的代码是一个单独的组件,我想创建多个它并为函数中的组件提供不同的数据。我该怎么做?

     const Home = ({ navigation }) => {
   <View
      // onPress={() => navigation.navigate("Detail")}
      style={externalStyle.image}
    >
      <Image
        style={{
          flex: 1,
          width: null,
          height: null,
          resizeMode: "contain",
        }}
        source={require("../images/apple-logo.png")}
      />
      <View style={externalStyle.card}>
        <Text
          style={{
            fontWeight: "bold",
          }}
        >
          APPLE
        </Text>
        <Text
          style={{
            fontWeight: "bold",
            color: "#00a46c",
            paddingLeft: 30,
            paddingBottom: 30,
          }}
        >
          $127.83{" "}
        </Text>
      </View>
    </View>
  );
};
export default Home;

标签: react-native

解决方案


尝试这样的事情

// Assuming your data shape
const data = [
    {
    image: 'apple-logo.png',
    brand: "Apple",
    amount: '$127.83'
    },
    {
    image: 'googl-logo.png',
    brand: "google",
    amount: '$117.8'
    },
]

// From your parent component 
render() {
    return (
        data.map((item, index) => {
            return <InfoCard data={item} key={index}/>
        })
    )
}

// In your child component
const InfoCard = ({data}) =>{
    const {image, brand, amount } = data;
    return (
        <View style={externalStyle.image}>
            <Image source={require(`../images/${image}`)}/>
            <View style={externalStyle.card}>
            <Text>{brand}</Text>
            <Text>{amount}</Text>
        </View>
        </View>
    );
}


推荐阅读