react ref 如何使用
React Refs 的基本概念
Refs 提供了一种直接访问 DOM 节点或 React 组件实例的方式。通常用于需要直接操作 DOM 或触发组件方法的场景,例如输入框聚焦、动画控制等。
创建 Refs
使用 React.createRef() 或 useRef Hook 创建 ref 对象。
类组件中使用 createRef
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
函数组件中使用 useRef

function MyComponent() {
const myRef = React.useRef(null);
return <div ref={myRef} />;
}
访问 Refs
通过 ref 对象的 current 属性访问 DOM 节点或组件实例。
访问 DOM 节点

function TextInput() {
const inputRef = React.useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
访问类组件实例
class CustomInput extends React.Component {
focus() {
this.inputRef.current.focus();
}
render() {
return <input ref={this.inputRef} />;
}
}
function ParentComponent() {
const customInputRef = React.useRef(null);
const handleClick = () => {
customInputRef.current.focus();
};
return (
<div>
<CustomInput ref={customInputRef} />
<button onClick={handleClick}>Focus Custom Input</button>
</div>
);
}
回调 Refs
回调 ref 是一种动态设置 ref 的方式,适用于 ref 需要动态变化的情况。
function CallbackRefExample() {
let textInput = null;
const setTextInputRef = (element) => {
textInput = element;
};
const focusTextInput = () => {
if (textInput) textInput.focus();
};
return (
<div>
<input type="text" ref={setTextInputRef} />
<button onClick={focusTextInput}>Focus Input</button>
</div>
);
}
转发 Refs(Forwarding Refs)
通过 React.forwardRef 将 ref 传递给子组件,适用于高阶组件或封装通用逻辑的组件。
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="fancy-button">
{props.children}
</button>
));
function App() {
const buttonRef = React.useRef(null);
return (
<div>
<FancyButton ref={buttonRef}>Click Me</FancyButton>
</div>
);
}
注意事项
- 避免过度使用 refs,优先使用 React 的状态和属性机制。
- 函数组件没有实例,不能直接通过 ref 访问,除非使用
forwardRef或useImperativeHandle。 - 在组件挂载后(
componentDidMount或useEffect)才能安全访问 ref。






