2 回答

TA貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以對(duì)代碼進(jìn)行一些更改
將顏色選擇移至 ListItem 并傳遞一個(gè) prop 來(lái)決定
無(wú)需在項(xiàng)目本身內(nèi)創(chuàng)建整個(gè)樣式,您可以傳遞要覆蓋的樣式
因此,要執(zhí)行此操作,您必須從列表項(xiàng)開(kāi)始
<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>
并且您的長(zhǎng)按處理程序應(yīng)如下所示更改,這會(huì)將標(biāo)記的屬性設(shè)置為您用來(lái)決定上面顏色的狀態(tài)
? const longPressHandler = (key) => {
? ? const updatedTodos = [...todos];
? ? const item = updatedTodos.find((x) => x.key == key);
? ? item.marked = !item.marked;
? ? setTodos(updatedTodos);
? };

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
試試這個(gè)方法
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 函數(shù)
添加回答
舉報(bào)