在 React 中通过 ID 获取元素

在 React 中通过 ID 获取元素:

  1. 在元素上设置 ref 属性。
  2. 使用 current 属性访问 useEffect 钩子中的元素。
import {useRef, useEffect} from 'react';

export default function App() {
  const ref = useRef(null);

  useEffect(() => {
    // ?️ 使用 document.getElementById()
    const el = document.getElementById('my-element');
    console.log(el);

    // ?️ (better) use a ref
    const el2 = ref.current;
    console.log(el2);
  }, []);

  return (
    <div>
      <h2 ref={ref} id="my-element">
        Some content here
      </h2>
    </div>
  );
}

上述代码片段显示了如何使用 document.getElementById() 方法和通过 ref 按 ID 获取元素。

useRef() 钩子可以传递一个初始值作为参数。 该钩子返回一个可变的 ref 对象,其 .current 属性被初始化为传递的参数。

注意 ,我们必须访问 ref 对象的 current 属性才能访问我们设置 ref 属性的 h2 元素。

当我们将 ref prop 传递给元素时,例如 <div ref={myRef} />,React 将 ref 对象的 .current 属性设置为对应的 DOM 节点。

我们将一个空的依赖数组传递给 useEffect 钩子,所以它只会在组件挂载时运行。

useEffect(() => {
  // ?️ 使用 document.getElementById()
  const el = document.getElementById('my-element');
  console.log(el);

  // ?️ (better) use a ref
  const el2 = ref.current;
  console.log(el2);
}, []);

我们使用了 useEffect 钩子,因为我们想确保元素上已经设置了 ref 并且元素已经被渲染到 DOM。

或者,如果我们无权访问该元素并且无法在其上设置 ref 道具,则可以使用 document.getElementById 方法。

useEffect(() => {
  // ?️ 使用 document.getElementById()
  const el = document.getElementById('my-element');
  console.log(el);
}, []);

我们必须在 useEffect 钩子中或发生事件时调用 document.getElementById() 方法。

这是一个在事件发生时通过 ID 获取元素的示例。

import {useRef} from 'react';

export default function App() {
  const ref = useRef(null);

  const handleClick = () => {
    // ?️ 使用 document.getElementById()
    const el = document.getElementById('my-element');
    console.log(el);

    // ?️ (better) use a ref
    const el2 = ref.current;
    console.log(el2);
  };

  return (
    <div>
      <h2 ref={ref} id="my-element">
        Some content here
      </h2>

      <button onClick={handleClick}>Click</button>
    </div>
  );
}

在 React 中通过 ID 获取元素

在事件处理函数中也可以通过 ID 选择元素或使用 ref。

如果我们尝试通过 ID 或直接在函数组件的 render 方法中通过其 ref 获取元素,则我们尝试访问的元素可能尚未渲染。

useEffect 钩子在组件中的 DOM 元素已经渲染到 DOM 之后运行,因此如果具有提供的 id 的元素存在,它将被选中。