React Native中多个TouchableOpacity点击全部同步切换状态如何解决?
你可以通过将单值状态改为对象类型来存储每个按钮的独立状态,不需要拆分现有组件结构,具体修改如下:
核心修改逻辑
- 将
isPressed状态从布尔值改为对象,用食材名称作为唯一key存储对应按钮的选中状态 - 重写按压处理函数,接收食材名参数,仅切换对应项的状态
- 每个按钮的背景样式判断改为读取对应食材的状态值
修改后完整代码
import { useState } from 'react'; import { ScrollView, Button, View, TouchableOpacity, Image, Text, StyleSheet } from 'react-native'; function Grocery({ navigation }) { // 状态改为对象,存储每个食材的独立选中状态 const [isPressed, setIsPressed] = useState({ pasta: false, eggs: false, fish: false }); // 按压函数接收食材名参数,仅更新对应项的状态 const onPress = (ingredient) => { setIsPressed(prev => ({ ...prev, [ingredient]: !prev[ingredient] })); }; return ( <ScrollView> <Button title="home" onPress={() => {FindMatch(GetIngridients());navigation.navigate("MatchedRecipiesScreen");}}>press</Button> <View style={styles.container}> <TouchableOpacity style={styles.button} onPress={() => {AddToPanetry("pasta");onPress("pasta");}} > <View style={isPressed.pasta && styles.pressedButtonStyle} /> <Image style={styles.imageright} source={require('../assets/Pastaa.jpg')} /> <Text> pasta</Text> </TouchableOpacity> <TouchableOpacity onPress={() => {AddToPanetry("eggs");onPress("eggs");}} > <View style={isPressed.eggs && styles.pressedButtonStyle} /> <Image style={styles.imageleft} source={require('../assets/eggs.jpg')} /> <Text>eggs</Text> </TouchableOpacity> <TouchableOpacity onPress={() => {AddToPanetry("fish");onPress("fish");}} > <View style={isPressed.fish && styles.pressedButtonStyle} /> <Image style={styles.imageleft} source={require('../assets/fish.jpg')} /> <Text>fish</Text> </TouchableOpacity> </View> </ScrollView> ); } const styles = StyleSheet.create({ container: { flexDirection: "row", flexWrap: "wrap", padding: 50, justifyContent: 'space-between', }, imageleft: { borderRadius: 80, borderWidth:2, borderColor:'black', height: 120, width: 150, padding:25 }, button: { alignItems: "center", }, tinyLogo: { width: 50, height: 50, }, pressedButtonStyle: { position:"absolute", width:150, height:121, backgroundColor:'black', opacity:0.6, zIndex:100, borderRadius:80 }, imageright: { borderRadius: 80, borderWidth:2, borderColor:'black', height: 120, width: 150, padding:25 } });
如果后续需要新增食材按钮,仅需要在useState初始对象中新增对应食材的key,在新按钮的按压事件中传入对应食材名即可,无需修改其他逻辑。
内容的提问来源于stack exchange,提问作者DavidB
相关产品推荐
相关产品推荐

