我试图在用户点击它后立即更改平面列表项的背景颜色。这里的问题是数组已更新,但该选定项目的背景颜色未更改。
我想要做的是-单击平面列表项后,该行的背景颜色应该会改变,但不会改变。以下是我尝试过的代码。
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
let topData = [
{
id: '1',
Name: 'Daily Oprations',
selected: false,
},
{
id: '2',
Name: 'Financials',
selected: false,
},
{
id: '3',
Name: 'Sharing',
selected: false,
},
{
id: '4',
Name: 'Common Questions',
selected: false,
},
];
const HelpDetails = () => {
const [data, setData] = useState([]);
useEffect(() => {
setData(topData)
}, []);
const setSelectedIndex = (index) => {
topData.map((e, i) => e.selected = (index == i))
setData(topData)
}
const renderItem = ({ item, index }) => {
console.log(item);
return (
<TouchableOpacity onPress={() => setSelectedIndex(index)} style={[item.selected ? styles.greenbg : styles.whitebg, styles.storeInformationView]}>
<Text style={[item.selected ? styles.whitetext : null, styles.name]}>{item.Name}</Text>
</TouchableOpacity>
);
};
return (
<FlatList
data={data}
renderItem={renderItem}
/>
);
};
export default HelpDetails;
const styles = StyleSheet.create({
greenbg: {
backgroundColor: 'green'
},
whitebg: {
backgroundColor: 'white',
},
storeInformationView: {
//backgroundColor: APP_COLOR.GREEN_COLOR,
borderRadius: 12,
padding: 18,
elevation: 15,
marginHorizontal: 10,
marginTop: 15,
marginBottom: 17,
},
whitetext: {
color: 'white'
},
name: {
fontSize: 15,
fontWeight: 'bold',
},
})
const DATA = [
{
id: '1',
Name: 'Daily Operations',
selected: true,
},
{
id: '2',
Name: 'Financials',
selected: false,
},
{
id: '3',
Name: 'Sharing',
selected: false,
},
{
id: '4',
Name: 'Common Questions',
selected: false,
},
];