react的hooks中如何获取ref
获取 ref 的常用方法
在 React Hooks 中,可以通过 useRef Hook 创建 ref,并将其附加到 DOM 元素或组件实例上。以下是几种常见的使用方式:
创建并绑定 ref
import { useRef } from 'react';
function MyComponent() {
const myRef = useRef(null);
return <div ref={myRef}>This is a ref example</div>;
}
访问 ref 当前值
通过 ref.current 可以访问到实际的 DOM 节点或组件实例:

function MyComponent() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</>
);
}
在自定义组件中使用 ref
默认情况下,函数组件不能直接接收 ref 属性。需要使用 forwardRef 来转发 ref:
定义可接收 ref 的组件

const CustomInput = forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
function ParentComponent() {
const inputRef = useRef(null);
return <CustomInput ref={inputRef} />;
}
动态绑定多个 ref
当需要管理多个 ref 时,可以使用 ref 回调函数或者对象存储多个 ref:
使用 ref 回调
function MultiRefComponent() {
const refs = useRef([]);
const setRef = (index) => (el) => {
refs.current[index] = el;
};
return (
<>
{[1, 2, 3].map((item, index) => (
<div key={item} ref={setRef(index)}>
Item {item}
</div>
))}
</>
);
}
注意事项
- ref 的值会在组件挂载后更新,初始值为
null - 修改 ref 不会触发组件重新渲染
- 避免在渲染过程中修改 ref,应在事件处理或副作用中操作
- 对于函数组件,必须使用
forwardRef才能接收 ref






