简体   繁体   English

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

[英]Can I use document.getElementByID in React

I am having a songKey array as a STATE. Its data populates from API. I am rendering JSX using this array data.我有一个 songKey 数组作为 STATE。它的数据从 API 填充。我正在使用这个数组数据渲染 JSX。 I like to add useRef in order to refer elements from the JSX.我喜欢添加 useRef 以引用 JSX 中的元素。 Is it possible to add useRef hooks via code automatically?是否可以通过代码自动添加 useRef 挂钩? or shall I use document.getElementById() function to refer elements?还是应该使用 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;
  };

I dont recommend using dom elements directly in React but if you are using it anyways then you can do it in way我不建议直接在 React 中使用 dom 元素,但如果你无论如何都在使用它,那么你可以用 way

use useRef in parent element then simply use querySelectorAll then use childs with index value of that array to access them directly在父元素中使用useRef然后简单地使用querySelectorAll然后使用具有该数组索引值的子元素直接访问它们

see the Example例子

main.jsx主.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