I am rendering 5 buttons with 5 different colors on my app but when I click one button, all buttons change to the same color. I would like to change only the state of the button I am clicking and other buttons remain the default color.
I would really appreciate your assistance. Here is the code below:
const buttonArray = [
{ value: 'red', name: 'tomato' },
{ value: 'green', name: 'apple' },
{ value: 'blue', name: 'berry' },
{ value: 'yellow', name: 'banana' },
{ value: 'orange', name: 'orange' }
]
const [buttonCol, setButtonCol] = useState(null)
const [isSelected, setIsSelected] = useState(false)
function selectedBtn(index) {
buttonArray.map((btn, ind) => {
if (buttonArray.indexOf(btn) === index) {
setIsSelected(!isSelected)
setButtonCol(btn.value)
}
})
}
return(
<View style={styles.button}>
{ buttonArray.map((button, index) => {
return (
<TouchableOpacity
style={[globalStyles.selectButton, isSelected ? { backgroundColor: buttonCol } : { backgroundColor: globalColors.iconGreyColor }]}
onPress={() => selectedBtn(index) }>
<Text style={{ color: '#fff' }}>{button.name}</Text>
</TouchableOpacity>
)})
}
</View>
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…