Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

javascript - How to toggle the state of an item inside a map funtion

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);
};

and that's the map function

<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

enter image description here

Here is the full code: https://snack.expo.io/KIiRsDPQv

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do one of following options

  1. change state to an array
const [selectedActivity, setSelectedActivity] = useState(Array.from({ length: activitiesObject.length }, _ => false))

const toggleSelectedActivity = (index) => 
        setSelectedActivity(prev => prev.map((bool, i) => i == index ? !bool : bool))

while passing the index to function, and use selectedActivity[i] ? ...

  1. extract
 <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> 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...