ReactJS Hook 模式 ~UseImperativeHandle~

发布: (2026年1月12日 GMT+8 16:52)
1 分钟阅读
原文: Dev.to

Source: Dev.to

useImperativeHandle 允许子组件通过 ref 向父组件公开特定的方法。当你需要以命令式方式调用子组件的函数时(例如聚焦输入框),这种模式非常有用。useImperativeHandle 并不会暴露整个 DOM 节点,而是可以只公开一个特定的方法,例如 focusInner

示例

import { useRef, useImperativeHandle } from "react";

function CustomInput({ ref, ...rest }) {
  const localRef = useRef();

  useImperativeHandle(ref, () => ({
    focusInner: () => {
      localRef.current.focus();
    },
  }));

  return ;
}

function App() {
  const inputRef = useRef();

  const handleFocus = () => {
    inputRef.current.focusInner();
  };

  return (
    
      
      
      Focus Input
    
  );
}

export default App;

useImperativeHandle

Back to Blog

相关文章

阅读更多 »

使用 Tailwind v4 与 next-themes 实现暗黑模式

安装 ```bash npm install next-themes ``` 在 `main.jsx`/`tsx` 中设置 ```tsx import { ThemeProvider } from 'next-themes'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; // 其他代码... ```