react-native - 使用函数多次生成示例组件 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;
解决方案
尝试这样的事情
// 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>
);
}
推荐阅读
- python - Google API 按 ID 搜索文件夹
- system-verilog - 在系统verilog中的for循环内fork join
- java - 如何在 build.xml 中为 java 中的特定测试类添加 VM 选项?
- python - 如何添加通过终端创建的环境
- javascript - 对象的 SOAP 文本值
- uri - REST URI - 使用 ID 数组获取资源批次
- flutter - 添加 firebase_messaging 后无法为 iOS 构建
- docker - Dockerfile 的 WORKDIR 是否根据主机或容器指定工作目录?
- javascript - Javascript .sort() 返回的真/假与预期不同
- html - 如何使嵌套表列的宽度等于父级