【发布时间】:2020-05-29 14:16:07
【问题描述】:
我有 5 个用 touchableopacity 包装的选项。我希望当单击一个选项时颜色变为绿色。如果我单击另一个选项,则前一个选项变为灰色,新选项为绿色。有人可以帮我编码吗?我不想写一堆 IF 语句。我觉得它的代码很糟糕,并且有一种更快的方法可以实现我的目标。不要介意那里的警报功能,我只有在最初设置可触摸不透明度时才拥有它。
const [angryColor, setAngryColor] = useState('grey')
const [sadColor, setEmojiSad] = useState('grey')
const [neutral, setNuetral] = useState('grey')
const [happyColor, setHappyColor] = useState('grey')
const [laughColor, setLaugh] = useState('grey')
function toggleAngry(){
if (angryColor === 'grey'){
setAngryColor('green')
} else {
setAngryColor('grey')
}
}
return(
<View style={styles.screen}>
<View style={styles.container}>
<View style={styles.emojiView}>
<TouchableOpacity onPress={() => toggleAngry()}>
<FontAwesome5 name="angry" size={40} color={angryColor}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => Alert.alert('clicked')}>
<Entypo name="emoji-sad" size={40} color={sadColor}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => Alert.alert('clicked')}>
<Entypo name="emoji-neutral" size={40} color={neutral} />
</TouchableOpacity>
<TouchableOpacity onPress={() => Alert.alert('clicked')}>
<Entypo name="emoji-happy" size={40} color={happyColor}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => Alert.alert('clicked')}>
<FontAwesome5 name="laugh-beam" size={40} color={laughColor} />
</TouchableOpacity>
</View>
【问题讨论】:
标签: react-native use-state touchableopacity