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 函数
添加回答
举报