简体   繁体   English

如何在 React 中正确更改 2 个状态?

[英]How do I change 2 states properly in React?

I have 2 spans and state for them:我有 2 个跨度和 state 供他们使用:

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.我了解如何更改每个跨度的isActive属性。 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.我需要的是,如果我单击一个跨度,并且它的属性isActive变为 true,另一个跨度isActive需要变为 false,并且对于第二个跨度相同。 How to do it properly in handleSorterClick function?如何在handleSorterClick function中正确执行?

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这样,如果您想增加跨度并想使用n span而不是2您只需将它们添加到您的sorterTabs变量

I think it would be easier to create a state for each span, map the spans, and control things that way.我认为为每个跨度创建 state、map 跨度并以这种方式控制事物会更容易。 This way if your app grows you only have to create a new state for each span.... or even use the useContext hook or redux, but that does not apply here.这样,如果您的应用程序增长,您只需为每个跨度创建一个新的 state ......甚至使用 useContext 挂钩或 redux,但这不适用于此处。 This would be my logic.这将是我的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM