本文介绍了如何在地图功能内切换项目的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试选择标签,问题是,我不知道如何为地图中的每个项目设定一个状态,现在我只有一个状态,当然,它将改变所有项目.
I'm trying to make a tag selection, the problem is, I don't know how to make a state for each item in the map, right now I have just one state, that, of course, will change all items.
那是状态和切换状态的功能
That's the state and the function to toggle the state
const [selectedActivity, setSelectedActivity] = useState(false);
const toggleSelectedActivity = () => {
setSelectedActivity(!selectedActivity);
};
这就是地图功能
<View style={styles.tags}>
{activitiesObject.map((data, i) => (
<TouchableOpacity
key={data.activity}
onPress={() => toggleSelectedActivity(i)}
>
<Text style={selectedActivity ? styles.selectedTag : styles.tagsText}>
{data.activity}
</Text>
</TouchableOpacity>
))}
</View>;
下图显示了每次用户选择标签时我期望发生的事情
the image below shows what I expect to happen every time the user selects a tag
这里是完整代码:: https://snack.expo.io/KIiRsDPQv
推荐答案
您可以执行以下选项之一
You can do one of following options
- 将状态更改为数组
const [selectedActivity, setSelectedActivity] = useState(Array.from({ length: activitiesObject.length }, _ => false))
const toggleSelectedActivity = (index) =>
setSelectedActivity(prev => prev.map((bool, i) => i == index ? !bool : bool))
,同时将索引传递给函数,并使用 selectedActivity [i]?...
while passing the index to function, and use selectedActivity[i] ? ...
- 提取
<TouchableOpacity key={data.activity} onPress={() => toggleSelectedActivity(i)}>
<Text style={selectedActivity ? styles.selectedTag : styles.tagsText}>{data.activity}</Text>
</TouchableOpacity>
到其自己的组件,并在其中声明状态
to its own component, and inside it declare the state
{activitiesObject.map((data, i) => <MyComp data={data} i={i} />
const MyComp = ({ data, i }) => {
const [selectedActivity, setSelectedActivity] = useState(false)
return <TouchableOpacity key={data.activity} onPress={() => setSelectedActivity(prev => !prev)}>
<Text style={selectedActivity ? styles.selectedTag : styles.tagsText}>{data.activity}</Text>
</TouchableOpacity>
}
这篇关于如何在地图功能内切换项目的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!