document.querySelector 在我的 React 组件中不起作用

document.querySelector is not working in my react component

function Slider() {
  const track=document.querySelector('.slide__track')//To access the div with class slide track
  console.log(track);
  return (
    <div className="slider">
      <i className="fas fa-chevron-left"></i>
      <div className="head">
        <h1 className="title">Based on your last search</h1>
        <h6>View more</h6>
      </div>
      <div className="slider_container">
        <ul className="slider__track">
          <li className="slider__items">
            <Card />
          </li>
        </ul>
      </div>
      <i className="fas fa-chevron-right"></i>
    </div>
  );
}

我无法使用 class slide__track 访问 div。 这里有什么问题? 或者我如何访问该元素?

我认为这是因为 运行 在 DOM 渲染之前。将轨道代码移入useEffect.

import {useEffect} from "react";

function Slider() {

  useEffect(() => {
    const track=document.querySelector('.slide__track')//To access the div with class slide track
    console.log(track);
  });

  return (
    <div className="slider">
      <i className="fas fa-chevron-left"></i>
      <div className="head">
        <h1 className="title">Based on your last search</h1>
        <h6>View more</h6>
      </div>
      <div className="slider_container">
        <ul className="slider__track">
          <li className="slider__items">
            <Card />
          </li>
        </ul>
      </div>
      <i className="fas fa-chevron-right"></i>
    </div>
  );
}

尝试在 useEffect() 中使用此代码

useEffect(() => {
    const track = document.querySelector('.slide__track')
    // have access to it
}, []);

您可能应该使用 ref 来访问 React 中的 dom 元素。请参阅文档:https://reactjs.org/docs/refs-and-the-dom.html - 原因是,如果循环中有以下内容,或者页面上有多个实例,则需要更加小心选择器方法。

import React, { useRef, useEffect } from 'react';

function Slider() {


  const slideTrackRef = useRef(null);

  useEffect(() => {
    if (slideTrackRef && slideTrackRef.current) {
      console.log(slideTrackRef.current);
    }
  }, [slideTrackRef]);

  return (
    <div className="slider">
      <i className="fas fa-chevron-left" />
      <div className="head">
        <h1 className="title">Based on your last search</h1>
        <h6>View more</h6>
      </div>
      <div className="slider_container">
        <ul className="slider__track" ref={slideTrackRef}>
          <li className="slider__items">
            <p>tst</p>
          </li>
        </ul>
      </div>
      <i className="fas fa-chevron-right" />
    </div>
  );
}

export default Slider;