React18之获取DOM(学习笔记)

2026-03-02  本文已影响0人  kevision

React中获取DOM


在 React 组件中获取/操作 DOM,需要使用 useRef React Hook钩子函数,分为两步:

  1. 使用useRef创建 ref 对象,并与 JSX 绑定
image.png
  1. 在DOM可用时,通过 inputRef.current 拿到 DOM 对象
image.png

ref操作子组件


要想操作子组件,需要用forwardRef包住子组件函数,并且用useImperativeHandle暴露子组件的属性和方法。

import { forwardRef, useState, useImperativeHandle, useRef } from 'react';

const Son = forwardRef((props, ref) => {
  const [count] = useState(0);
  const inputRef = useRef(null);
  const handleClick = () => {
    console.log('click');
  };
  const focus = () => {
    inputRef.current.focus();
  };
  // 相当于vue3中的defineExpose
  useImperativeHandle(ref, () => {
    return {
      handleClick,
      focus,
      count,
    };
  }, [count]);
  return <input ref={inputRef} />;
});

const App = () => {
  const sonRef = useRef(null);
  const handleShowSonRef = () => {
    console.log('sonRef count', sonRef.current.count);
    sonRef.current.focus();
  };
  return (
    <div>
      <div>
        <button onClick={handleShowSonRef}>show sonRef</button>
      </div>
      <Son ref={sonRef} />
    </div>
  );
};
export default App;
上一篇 下一篇

猜你喜欢

热点阅读