簡體   English   中英

我可以在 React 中使用 document.getElementByID 嗎?

[英]Can I use document.getElementByID in React

我有一個 songKey 數組作為 STATE。它的數據從 API 填充。我正在使用這個數組數據渲染 JSX。 我喜歡添加 useRef 以引用 JSX 中的元素。 是否可以通過代碼自動添加 useRef 掛鈎? 還是應該使用 document.getElementById() function 來引用元素?

  const [songKey, songKeyController] = useState([]);
  ...
  ...
  ...
  ...
  ...
  const renderLyrics = () => {
    let lyrics = [];
    if (songKey) {
      lyrics = songKey.map((key) => (
        <div key={key} className={`lyrics_container ${key}`}>
          <div className="lyrics_data tamil-font">
            {props.currentSong.Data[key]}
          </div>
        </div>
      ));
    }
    return lyrics;
  };

我不建議直接在 React 中使用 dom 元素,但如果你無論如何都在使用它,那么你可以用 way

在父元素中使用useRef然后簡單地使用querySelectorAll然后使用具有該數組索引值的子元素直接訪問它們

例子

主.jsx

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

export default function Main() {
  const EL = useRef(null);

  const [data, setData] = useState(["First", "Second", "Third", "Fourth"]);

  useEffect(() => {
    const childs = EL.current.querySelectorAll(".child");

    // fun demo
    let index = 0;
    setInterval(() => {
      const curr = childs[index % childs.length];
      childs.forEach((each) => (each.style.background = ""));
      curr.style.background = "red";
      console.log(curr);
      index++;
    }, 1000);
    // fun demo

  }, [data]);

  return (
    <div className="root" ref={EL}>
      {data.map((each, i) => {
        return (
          <div className="child" key={i}>
            {each}
          </div>
        );
      })}
    </div>
  );
}

暫無
暫無

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

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