根据React.js中的状态值切换按钮值

t5zmwmid  于 2022-10-15  发布在  React
关注(0)|答案(1)|浏览(198)

我正在显示不同的汽车和一个按钮,用于添加或删除用户所做的选择。如何让按钮单独更改状态?到目前为止,它将所有按钮的状态更改为一个值。

const cars = [
  { name: "Benz", selected: false },
  { name: "Jeep", selected: false },
  { name: "BMW", selected: false }
];

export default function App() {
  const isJeepSelected = true;
  const isBenzSelected = true;

  return (
    <div className="App">
      {cars.map((values, index) => (
        <div key={index}>
          <Item
            isBenzSelected={isBenzSelected}
            isJeepSelected={isJeepSelected}
            {...values}
          />
        </div>
      ))}
    </div>
  );
}

const Item = ({ name, isBenzSelected, isJeepSelected }) => {
  const [toggle, setToggle] = useState(false);
  const handleChange = () => {
    setToggle(!toggle);
  };

  if (isBenzSelected) {
    cars.find((val) => val.name === "Benz").selected = true;
  }

  console.log("cars --> ", cars);
  console.log("isBenzSelected ", isBenzSelected);
  console.log("isJeepSelected ", isJeepSelected);

  return (
    <>
      <span>{name}</span>
      <span>
        <button onClick={handleChange}>
          {!toggle && !isBenzSelected ? "Add" : "Remove"}
        </button>
      </span>
    </>
  );
};

我使用Code Sandbox创建了一个工作示例。有人能帮帮忙吗?

0sgqnhkj

0sgqnhkj1#

这里有太多的硬编码。如果你有300辆车呢?您必须编写300个布尔useState钩子调用,如果您有一个任意的API有效负载(通常情况下),它仍然不是动态的。
尝试考虑如何泛化您的逻辑,而不是像"Benz"Jeep那样对值进行硬编码。这些概念与任意的数据内容联系得太紧密了。
cars看起来应该是状态,因为你是从React中变异出来的。
以下是另一种方法:

const App = () => {
  const [cars, setCars] = React.useState([
    {name: "Benz", selected: false},
    {name: "Jeep", selected: false},
    {name: "BMW", selected: false},
  ]);

  const handleSelect = i => {
    setCars(prevCars => prevCars.map((e, j) =>
      ({...e, selected: i === j ? !e.selected : e.selected})
    ));
  };

  return (
    <div className="App">
      {cars.map((e, i) => (
        <div key={e.name}>
          <Item {...e} handleSelect={() => handleSelect(i)} />
        </div>
      ))}
    </div>
  );
};

const Item = ({name, selected, handleSelect}) => (
  <React.Fragment>
    <span>{name}</span>
    <span>
      <button onClick={handleSelect}>
        {selected ? "Remove" : "Add"}
      </button>
    </span>
  </React.Fragment>
);

ReactDOM.createRoot(document.querySelector("#app"))
  .render(<App />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div>

考虑为元素生成唯一ID,而不是使用索引或假定名称是唯一的。crypto.randomUUID()是实现这一点的一种便捷方法。

相关问题