我想在单击时将动态加载的组件的背景颜色更改为黄色。为此,我必须使用useState数组保存每个已加载组件的颜色。
代码在下面给出
import React, {useState,useEffect} from "react";
import { Dimensions, Image, FlatList,StatusBar,TouchableOpacity} from "react-native";
import { Container,Content, Item, Card,CardItem,View , Text, Icon, Button , Left, Body,Right} from "native-base";
import {serverAddr} from '../App'
const SelectService =({route,navigation})=>{
const { id } = route.params;
const { gname } = route.params;
const [mapDetails, setMapDetails] = useState([]);
const [checkedItems, setCheckedItems] = useState({});
var myServices=[]
var colorList={};
useEffect(() => {
const user= new FormData();
user.append("id", id);
fetch(serverAddr+'/getBooking.php',{
method:'post',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body:user
})
.then((response) => response.json())
.then((responseJson) => {
setMapDetails(responseJson);
responseJson.forEach(function(details){
colorList[details.ID]="white";
})
setCheckedItems(colorList);
console.log(checkedItems);
});
},[])
const handleChange = (id,name) => {
colorList[id]="yellow";
setCheckedItems(colorList);
console.log(colorList);
}
mapDetails.forEach(function(details){
myServices.push(
<Card>
<TouchableOpacity onPress={()=>handleChange(details.ID,details.sname)}>
<CardItem style={{backgroundColor:checkedItems[details.ID]}}>
<Left>
<Icon name="bus" />
<Body>
<Text>{details.sname}</Text>
<Text>{details.price} Rs</Text>
</Body>
</Left>
</CardItem>
</TouchableOpacity>
</Card>
)
})
return(
<Container>
<Content>
<View>
{myServices}
</View>
</Content>
</Container>
)
}
export default SelectService;
上面的代码获取功能中的将返回3个对象,该对象用于创建3个Card组件。
当我单击这些Card组件时,我希望它们的背景颜色变为“黄色”。上面的代码帮助我将当前组件的背景颜色更改为“黄色”。 (当我单击其他组件时,以前的组件颜色会变回白色,而当前组件会变回白色)