我正在尝试更改此议程中仅一项的背景,但是使用我的代码,当我单击一个项目时,它会更改所有项目的背景颜色,而不仅仅是我单击的那个:单击项目屏幕之前的 屏幕点击后
问题在于只知道如何更改议程中一个项目的样式,而不是所有项目的样式。
这是我的代码:
import React, { useState } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
} from 'react-native';
import moment from 'moment';
import { Avatar, Card } from 'react-native-paper';
import {Agenda} from "react-native-calendars";
const timeToString = (time) => {
const date = new Date(time);
return date.toISOString().split('T')[0];
};
export default function calendarScreen () {
const [color, setColor] = useState(
{backgroundColor: 'white', backgroundColor2: 'white', texte: 'Disponible', pressed: false}
);
const changeColor = () => {
if (!color.pressed) {
setColor({backgroundColor: 'lightgreen', backgroundColor2: 'white', texte: 'Réservé', pressed: true})
} else {
setColor({backgroundColor: 'white', backgroundColor2: 'green', texte: 'Disponible', pressed: false})
}
};
const [items, setItems] = useState({});
const loadItems = (day) => {
setTimeout(() => {
for (let i = -15; i < 85; i++) {
const time = day.timestamp + i * 24 * 60 * 60 * 1000;
const strTime = timeToString(time);
if (!items[strTime]) {
items[strTime] = [];
const numItems = 1;
for (let j = 0; j < numItems; j++) {
items[strTime].push({
name: 'Disponible',
height: Math.max(50, Math.floor(Math.random() * 150)),
style: color.backgroundColor
});
}
}
}
const newItems = {};
Object.keys(items).forEach(key => {newItems[key] = items[key];});
setItems(newItems);
}, 1000);
};
const renderItem = (item, firstItemInDay) => {
return (
<TouchableOpacity style={{ marginTop: 17, marginRight: 10}} onPress={(changeColor)}>
<Card style={ { backgroundColor : color.backgroundColor }}>
<Card.Content>
<View style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}}>
<Text>{item.name}</Text>
<Avatar.Text label="J" />
</View>
</Card.Content>
</Card>
</TouchableOpacity>
)
};
return (
<View style={{flex:1}}>
<Agenda
items={items}
loadItemsForMonth={loadItems}
selected={'2020-09-23'}
renderItem={renderItem}
/>
</View>
)
}
非常感谢您的帮助