1
Begginer开发人员原生反应。
我正在处理设计模式的问题,我在同一个组件中有多个TouchableOpacity(我必须保持这种方式)。对于每一个,我都有onPress函数,它可以改变背景和反转方向。问题是,函数依赖于State current语句,当我单击其中一个语句时,每个人都在改变。
function Grocery({ navigation }) {
const [isPressed, setIsPressed] = useState(0);
const onPress = () => setIsPressed(!isPressed);
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();}} >
<View style={isPressed && styles.pressedButtonStyle} />
<Image style={styles.imageright} source={require('../assets/Pastaa.jpg')} />
<Text> pasta</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {AddToPanetry("eggs");onPress();}} >
<View style={isPressed && styles.pressedButtonStyle} />
<Image style={styles.imageleft} source={require('../assets/eggs.jpg')} />
<Text>eggs</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {AddToPanetry("sugar");onPress();}} >
<View style={isPressed && styles.pressedButtonStyle} />
<Image style={styles.imageleft} source={require('../assets/sugar.jpg')} />
<Text>eggs</Text>
</TouchableOpacity>
const styles = StyleSheet.create({
container: {
flexDirection: "row",
flexWrap: "wrap",
padding: 50,
flexWrap: 'wrap',
justifyContent: 'space-between',
}
,
imageleft: {
borderRadius:100,
borderWidth:2,
borderColor:'black',
height: 120,
width: 150,
borderRadius: 80,
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:100,
borderWidth:2,
borderColor:'black',
height: 120,
width: 150,
borderRadius: 80,
padding:25
}
});在这种情况下,谁能告诉我在布尔型数组中使用UseState的正确方法?
tnx。
发布于 2021-10-18 16:27:05
您可以使用render prop模式来封装给您带来麻烦的逻辑。
const ToggleWrapper = ({render, onPress}) => {
const [isPressed, setIsPressed] = useState(0);
const _onPress = () => setIsPressed(!isPressed);
return <TouchableOpacity onPress={() => {_onPress();onPress();}} >
{render(isPressed)}
</TouchableOpacity>
}https://stackoverflow.com/questions/69619308
复制相似问题