初學者開發人員反應原生。
我正在處理設計模式問題,我在同一個組件中有多個 TouchableOpacity(我必須保持這種狀態)。對于每一個,我都有 onPress 功能,可以改變背景和反轉。問題是該函式依賴于 State current statment,當我點擊其中一個時,evreyone 正在改變。
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>
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
}
});
uj5u.com熱心網友回復:
設定狀態陣列
const [isPressed, setIsPressed ] = useState([true, false, false, false, false]);
這是一個示例
uj5u.com熱心網友回復:
你也可以嘗試這樣的事情:
const [isPressed, setIsPressed ] = React.useState('first');
...
<TouchableOpacity style={styles.button} onPress={() => setIsPressed('first')>
<View style={isPressed === 'first' ? styles.pressedButtonStyle : null} />
</TouchableOpacity>
...
<TouchableOpacity style={styles.button} onPress={() => setIsPressed('second')>
<View style={isPressed === 'second' ? styles.pressedButtonStyle : null} />
</TouchableOpacity>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/319246.html
