我的onPress函数有问题,我必须在每个TouchableOpacity上单击两次才能更改样式。在Web开发方面,它工作得很好,我使用expo ios iPhone来查看应用程序,但它不像在Web上那样工作。我不知道为什么,但我必须点击两次,然后它的变化。任何帮助吗?
const Test = ({ navigation }) => {
const itemsData = GetGroceryIngridients();
const [items, setItems] = useState(itemsData);
const handleSelectItem = (selectedItemIndex) => {
const itemsToSelect = items.map((item, index) => {
if (selectedItemIndex === index) item.pressed = !item.pressed;
return item;
}, []);
setItems(itemsToSelect);
// your logic here
AddToPanetry(items[selectedItemIndex].label);
};
const renderItem = (item, index) => {
const isSelected = items[index].pressed;
return (
<TouchableOpacity
style={[styles.button, isSelected && styles.selectedButton]}
onPress={() => handleSelectItem(index)}
>
{
<Image
style={{ height: 110, width: 100, borderRadius: 50 }}
source={item.image}
/>
}
<Text>{item.name}</Text>
</TouchableOpacity>
);
};
return (
<View>
<ScrollView>
<TouchableOpacity
onPress={() => navigation.navigate("IngridientsScreen")}
>
<Ionicons
style={{ width: 50, height: 50 }}
name="arrow-back-circle-sharp"
size={50}
color="#eb344f"
/>
</TouchableOpacity>
{itemsData.map((item, index) => renderItem(item, index))}
</ScrollView>
</View>
);
};
const styles = StyleSheet.create({
button: {
opacity: 1,
padding: 20,
},
selectedButton: {
opacity: 0.5,
},
});
export default Test;
My GroceryIngridients Array =
const GroceryIngridients = [
{
label: "pasta",
image: require("../assets/Pastaa.jpg"),
pressed: true,
},
{
label: "eggs",
image: require("../assets/eggs.jpg"),
pressed: true,
},
{
label: "white_flour",
image: require("../assets/whiteflour.jpg"),
pressed: false,
},
{
label: "rice",
image: require("../assets/rice.jpg"),
pressed: false,
},
{
label: "breadcrumbs",
image: require("../assets/breadcrumbs.jpg"),
pressed: false,
},
];
任何其他方式显示欢迎!!
似乎是一个小错误(应该循环状态)
改变这
{itemsData.map((item, index) => renderItem(item, index))}
{items.map((item, index) => renderItem(item, index))}