我正在使用map一次渲染多个按钮。我希望按下一个按钮的背景颜色会改变,但现在当我按下一个按钮时,所有按钮的颜色都会改变。我可以为每个按钮创建状态以查看它是否被选中,但是如果我有大量不实用的按钮。有什么解决方法吗?
const [selected, setSelected] = React.useState(false);
const genres = ["Adventure", "Arts", "Leisure", "Nature"];
const onSelect = () => setSelected(!selected);
buttons = () =>
genres.map((items) => (
<TouchableOpacity
key={items}
onPress={() => onSelect()}
style={[
styles.button,
{ backgroundColor: selected ? "#00cc00" : "#f2f2f2" },
]}
>
<Text style={{ fontSize: 18 }}>{items}</Text>
</TouchableOpacity>
));
编辑:我想一次选择多个按钮。如果我单击冒险和休闲,它们的按钮颜色都会改变,但其余部分保持不变。颜色可以在多次印刷机上切换
const [selected, setSelected] = React.useState(null);
const genres = ['Adventure', 'Arts', 'Leisure', 'Nature'];
buttons = () =>
genres.map(item => (
<TouchableOpacity
key={item}
onPress={() => setSelected(item)}
style={[styles.button, { backgroundColor: item === selected ? '#00cc00' : '#f2f2f2' }]}
>
<Text style={{ fontSize: 18 }}>{items}</Text>
</TouchableOpacity>
));
编辑:乘以所选
const [selected, setSelected] = React.useState([]);
const genres = ['Adventure', 'Arts', 'Leisure', 'Nature'];
const handlePress = genre =>
selected.includes(genre) ? setSelected(selected.filter(s => s !== genre)) : setSelected([...selected, genre]);
buttons = () =>
genres.map(item => (
<TouchableOpacity
key={item}
onPress={() => handlePress(item)}
style={[styles.button, { backgroundColor: selected.includes(genre) ? '#00cc00' : '#f2f2f2' }]}
>
<Text style={{ fontSize: 18 }}>{items}</Text>
</TouchableOpacity>
));