import { forwardRef, useRef } from 'react';
// 1. 使用 forwardRef 包裹子组件
const MyInput = forwardRef((props, ref) => {
// 2. 将收到的 ref 转发到内部的 input 元素上
return <input {...props} ref={ref} placeholder="点击按钮聚焦" />;
const inputRef = useRef(null);
const handleFocus = () => {
// 3. 现在 ref 指向的是子组件内部的 input DOM 节点
inputRef.current.focus();
<MyInput ref={inputRef} />
<button onClick={handleFocus} style={{ marginTop: '10px' }}>