javascript 在react js(map)中将活动类名设置为多个项并删除

uz75evzq  于 2023-01-29  发布在  Java
关注(0)|答案(3)|浏览(80)

我需要将活动类名设置为.map中的多个onclick项
我需要被点击的活动项目列表
单击的项目将以黄色突出显示,当我再次单击同一项目时,它将从活动列表项目中删除。

const [data, setData] = useState([]);
const [activeIndicies, setActiveIndicies] = useState(() =>
    data?.map(() => false)
);

useEffect(() => {
    // This data is coming from the API response
    const data = [
        { id: 1, name: "one" },
        { id: 2, name: "two" },
       { id: 3, name: "three" }
    ];
    setData(data);
}, []);

返回叙述

onClick={() => {
    setActiveIndicies(
        activeIndicies.map((bool, j) => (j === index ? true : bool))
    );
}}

Code Sandbox
谢谢你。

ddrv8njm

ddrv8njm1#

试试这个:

import "./styles.css";

import React, { useState, useEffect } from "react";

export default function App() {

const [data, setData] = useState([
{ id: 1, name: "one", active: false },
{ id: 2, name: "two", active: false },
{ id: 3, name: "three", active: false }
  ]);

  return (
    <div className="App">
      <h2>Set active className to multiple items on .map</h2>
      {data?.map((item, index) => {
        return (
          <p className={data[index].active ? "selected" : "notselected"}
         onClick={() => {
          setData((prevState) =>
            _.orderBy(
              [
                ...prevState.filter((row) => row.id !== item.id),
                { ...item, active: !item.active }
              ],
              ["name"],
              ["asc"]
            )
          );
        }}
      >
        {item.name}
      </p>
    );
  })}
</div>
  );
}
piv4azn7

piv4azn72#

您只需对代码进行一些小的更改就可以实现这一点:

// Changing the state value to an object so that it can
  // store the active value for exact item ids
  const [activeIndicies, setActiveIndicies] = useState({});

然后在.map()

....
        // Checking if there is any value for the item id which is being mapped right now.
        const selected = activeIndicies[item.id];
        return (
          <p
            className={selected ? "selected" : "notselected"}
            onClick={() => {
              /* Then setting the state like below where it toggles 
               the value for particular item id. This way if item is
               selected it will be deselected and vice-versa.
              */
              setActiveIndicies((prevState) => {
                const newStateValue = !prevState[item.id];
                return { ...prevState, [item.id]: newStateValue };
              });
            }}
           // Key is important :)
            key={item.id}
          >
            {item.name}
          </p>
        );
yk9xbfzb

yk9xbfzb3#

"你好,朋友们"
我用对我来说更方便的方式解决了这个问题)

const data = [
    { id: 1, name: "Ann", selected: true },
    { id: 2, name: "Serg", selected: false },
    { id: 3, name: "Boris", selected: true },
  ];
  //you don't even need to have a boolean field in the object - 
 //it will be added by itself on the first click on the element
 // const data = [{ name:"Ann", id:1}, { name:"Serg", id:2 },{ name:"Boris", id:3 },]
  const [users, setUsers] = useState(data); // no square brackets-[data]
  function handleActive(item) {
    setUsers((prev) => {
      return prev.map((itemName) => {
        if (itemName.name === item.name) {
          return { ...itemName, selected: !itemName.selected };
          // itemName.selected = !itemName.selected // or so
        }
        return itemName;
      });
    });
  }
      return (
    {
     users.map((item, i) => {
       // let current  = item.selected === true 
      // or so -> className={current === true ? 'users': ''}
          return (
            <div
              onClick={() => handleActive(item)}
              className={item.selected === true ? "active" : ""}
              key={i}
            >
              {item.name}
            </div>
          );
        })
      }
     );

相关问题