反应状态挂钩,toogle类,为什么两个元素都变为“活动”类?

问题描述 投票:0回答:1

希望你能帮助我。

为什么我的两个li元素都将活动类应用于它?

https://codesandbox.io/s/flamboyant-hofstadter-7rgz5

谢谢

reactjs toggle hook
1个回答
0
投票

在您当前的示例中,两个列表项共享相同的状态。

import React, { useState } from 'react';
import './styles.css';

const creditValues = [
  {
    month: 6,
    monthly: 102.72,
    interest: 24.36,
    cost: 616.32,
    total: 591.96,
  },
  {
    month: 12,
    monthly: 53.15,
    interest: 24.36,
    cost: 616.32,
    total: 591.96,
  },
];

const Item = ({ children }) => {
  const [active, setActive] = useState(false);

  return (
    <li
      className={active ? 'active' : 'noactive'}
      onClick={() => setActive(p => !p)}
    >
      {children}
    </li>
  );
};

const App = () => {
  return (
    <ul className="monthly-instalments">
      {creditValues.map((creditValue, index) => (
        <Item key={index}>{creditValue.month} months</Item>
      ))}
    </ul>
  );
};

export default App;

Edit cold-brook-tsdrs

© www.soinside.com 2019 - 2024. All rights reserved.