2 回答

TA貢獻1793條經驗 獲得超6個贊
您可以對代碼進行一些更改
將顏色選擇移至 ListItem 并傳遞一個 prop 來決定
無需在項目本身內創建整個樣式,您可以傳遞要覆蓋的樣式
因此,要執行此操作,您必須從列表項開始
<TouchableOpacity
? onLongPress={() => props.longPressHandler(props.item.key)}
? onPress={() => props.pressHandler(props.item.key)}>
? <Text
? ? style={[
? ? ? // this will make sure that only one style object is created
? ? ? styles.listItem,
? ? ? { backgroundColor: props.marked ? 'green' : 'white' },
? ? ]}>
? ? {props.item.todo}
? </Text>
</TouchableOpacity>
并且您的長按處理程序應如下所示更改,這會將標記的屬性設置為您用來決定上面顏色的狀態
? const longPressHandler = (key) => {
? ? const updatedTodos = [...todos];
? ? const item = updatedTodos.find((x) => x.key == key);
? ? item.marked = !item.marked;
? ? setTodos(updatedTodos);
? };

TA貢獻1995條經驗 獲得超2個贊
試試這個方法
const longPressHandler = (index) => {
const newTodos = [...todos];
newTodos[index].color = (newTodos[index].color && newTodos[index].color == 'green') ? 'white' : 'green';
setTodos(newTodos);
}
<FlatList
data={todos}
renderItem={( {item, index} ) => (
<ListItem
item={item}
index={index}
longPressHandler = {longPressHandler}
color={item.color || 'white'}
pressHandler = {pressHandler}
/>
)}
/>
export default function ListItem(props) {
return (
<TouchableOpacity onLongPress={() => props.longPressHandler(props.index)} >
.....
</TouchableOpacity>
)
}
注意:您必須將索引從 renderItem 傳遞到 ListItem,并從 ListItem 傳遞到 longPressHandler 函數
添加回答
舉報