Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How do I change 2 states properly in React?

I have 2 spans and state for them:

const Sorter = () => {
  const [sorterTabs, setSorterTabs] = useState([
    {id:'The cheapest', isActive: false },
    {id:'The fastest', isActive: false }
  ])

  const handleSorterClick = ({ target }) => {
    const newSorterTabs = [...sorterTabs]
    newSorterTabs.forEach((item) => {
      if (item.id === target.getAttribute('name')) {
        item.isActive = !item.isActive
      }
    })
    setSorterTabs(newSorterTabs)
  }

  return (
    <>
      {sorterTabs.map((item) => 
        <SorterSpan 
          key={item.id}
          onClick={handleSorterClick}
          name={item.id}
          className={item.isActive ? 'active' : ''}
        />
      )}
    </>
  )
}

const SorterSpan = ({name, onClick, className}) => {
  return (
    <span 
      onClick={onClick} 
      className={className}
      name={name}
    >
      {name}
    </span>
  )
}

I understand how I can change isActive property for each of span. What I need is if I click one span, and it's property isActive becomes true the other span isActive needs to become false and the same for the second span. How to do it properly in handleSorterClick function?


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

1 Answer

0 votes
by (71.8m points)

I think the better, cleaner and faster approach for what you're trying to do is this:

const Sorter = () => {
  const sorterTabs = [{ id: "The cheapest" }, { id: "The fastest" }];
  const [selected, setSelected] = useState("");

  const handleSorterClick = ({ target }) => {
    setSelected(target.name);
  };

  return (
    <>
      {sorterTabs.map((item) => (
        <SorterSpan
          key={item.id}
          onClick={handleSorterClick}
          name={item.id}
          className={selected === item.id ? "active" : ""}
        />
      ))}
    </>
  );
};

const SorterSpan = ({ name, onClick, className }) => {
  return (
    <span onClick={onClick} className={className} name={name}>
      {name}
    </span>
  );
};

in this way if you want to grow your spans and wanted to use n span instead of 2 you only need to add them to your sorterTabs variable


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...