【发布时间】:2021-04-12 07:45:04
【问题描述】:
我在我的应用程序上呈现 5 个具有 5 种不同颜色的按钮,但是当我单击一个按钮时,所有按钮都会变为相同的颜色。我只想更改我单击的按钮的状态,其他按钮保持默认颜色。
非常感谢您的帮助。下面是代码:
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>
)
【问题讨论】:
标签: javascript arrays react-native use-state