【React】标准库useRef: 获取dom

获取DOM

介绍

  • 在React组件中获取/操作DOM,需要使用 useRef 钩子函数。

示例

import { useRef } from "react"

function App() {

  // useRef生成ref对象
  const inputRef = useRef(null)

  const showDom = () => {
    console.dir(inputRef.current)
  }

  return (
    <div>
      {/* 绑定ref对象到dom标签 */}
      <input type="text" ref={inputRef} />
      {/* dom可用时(dom渲染生成完毕后才可用),通过 ref.current 获取dom */}
      <button onClick={showDom}>获取dom</button>
    </div>
  );
}
...
posted @ 2024-08-30 23:31  505donkey  阅读(23)  评论(0)    收藏  举报