簡體   English   中英

如何使用 React useRef hook 刪除 map 中的類

[英]How to use React useRef hook for removing classes within map

我是反應新手。 我正在嘗試將 onClick 事件添加到 div 元素,該元素將從另一個元素中刪除 className。 這些元素是 map 中循環的一部分。 我正在嘗試為此使用 useRef 掛鈎。 我特別不想切換類名,我想刪除它,就是這樣。 然后用來自另一個元素的另一個 onclick 事件將其添加回來。 此要求特定於我的應用程序。 我當前的代碼從最后一個元素中刪除了 className,而不是我的目標。 提前感謝您的幫助!

import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import "./styles.css";

export default function App() {
  const [kitchenItems, setkitchenItems] = useState([]);

  useEffect(() => {
    axios.get("./data.json").then((res) => {
      setkitchenItems(res.data.kitchen);
    });
  }, []);

  const navRef = React.useRef(null);

  const onRemoveClick = (e) => {
    navRef.current.classList.remove("red");
  };

  return (
    <main>
      {kitchenItems.map((item, index) => (
        <div key={index} className="item">
          <div onClick={onRemoveClick}>
            <h2>{item.name}</h2>
            <p ref={navRef} className="red">
              {item.text}
            </p>
          </div>
        </div>
      ))}
    </main>
  );
}

它在 CodeSandbox 中: https://codesandbox.io/s/lively-moon-d7mm3

將項目是否應具有 class 的指示符保存到kitchenItems state 中。 刪除參考。

  useEffect(() => {
    axios.get("./data.json").then((res) => {
      setkitchenItems(res.data.kitchen.map(item => ({ ...item, red: true })));
    });
  }, []);
const onRemoveClick = (i) => {
  setkitchenItems(
    kitchenItems.map((item, j) => j !== i ? item : ({ ...item, red: false }))
  );
};
<div onClick={() => onRemoveClick(i)}>
  <h2>{item.name}</h2>
  <p className={item.red ? 'red' : ''}>

您處理此問題的方式是使用 jQuery 完成的方式,即您更改 dom 元素。 在 React 中,您將改為更新 state 並讓組件呈現。 我在您的對象上添加了一個新屬性,但如果您願意,您可能有另一個列表或其他一些邏輯。

import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import "./styles.css";

export default function App() {
  const [kitchenItems, setkitchenItems] = useState([]);

  useEffect(() => {
    axios.get("./data.json").then((res) => {
      setkitchenItems(res.data.kitchen);
    });
  }, []);

  const onRemoveClick = (index) => {
    debugger;
    const tmpItems = [...kitchenItems];
    tmpItems[index].isRed = !tmpItems[index].isRed;
    setkitchenItems(tmpItems);
  };

  return (
    <main>
      {kitchenItems.map((item, index) => (
        <div key={index} className="item">
          <div onClick={() => onRemoveClick(index)}>
            <h2>{item.name}</h2>
            <p className={item.isRed ? "red" : ""}>{item.text}</p>
          </div>
        </div>
      ))}
    </main>
  );
}

在 CodeSandbox 中: https://codesandbox.io/s/keen-kirch-55whe?file=/src/App.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM