react ref 如何使用
React Refs 的基本概念
Refs 提供了一种方式,允许直接访问 DOM 节点或在 React 组件中创建的实例。主要用于需要直接操作 DOM 或访问组件内部状态的场景,比如聚焦输入框、触发动画或集成第三方 DOM 库。
创建 Refs
使用 React.createRef() 或 useRef Hook 创建 ref 对象。类组件使用 createRef,函数组件使用 useRef。
// 类组件
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
}
// 函数组件
function MyComponent() {
const myRef = React.useRef(null);
}
绑定 Refs 到 DOM 元素
通过 ref 属性将 ref 对象绑定到具体的 DOM 元素或组件实例上。
// 绑定到 DOM 元素
<input ref={this.myRef} /> // 类组件
<input ref={myRef} /> // 函数组件
// 绑定到类组件实例
<ClassComponent ref={this.myRef} />
访问 Refs
通过 ref 对象的 current 属性访问绑定的 DOM 节点或组件实例。
// 类组件中访问
componentDidMount() {
this.myRef.current.focus(); // 聚焦输入框
}
// 函数组件中访问
React.useEffect(() => {
myRef.current.focus();
}, []);
回调 Refs
另一种方式是使用回调函数形式的 ref,适用于动态绑定 ref 的场景。
<input ref={(node) => { this.inputRef = node; }} />
转发 Refs (Forwarding Refs)
通过 React.forwardRef 将 ref 传递给子组件,常用于封装高阶组件或库组件。
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="fancy-button">
{props.children}
</button>
));
// 使用
const ref = React.useRef(null);
<FancyButton ref={ref}>Click Me</FancyButton>
注意事项
- 避免过度使用 refs,优先通过 props 和状态管理数据流。
- 函数组件无法直接绑定 ref(除非使用
forwardRef),因为函数组件没有实例。 - 在
componentDidMount或useEffect中访问 ref,确保 DOM 已渲染完成。







