react中ref如何
在React中使用Ref
Ref在React中用于直接访问DOM节点或React组件实例。以下是几种常见的使用方法:
创建Ref
使用React.createRef()可以创建一个ref对象:

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
函数组件中使用Ref
函数组件需要使用useRef Hook:
function MyFunctionComponent() {
const myRef = useRef(null);
return <div ref={myRef} />;
}
访问Ref的值
通过ref的current属性访问DOM节点或组件实例:

componentDidMount() {
const node = this.myRef.current;
node.focus(); // 操作DOM节点
}
回调Ref
另一种方式是使用回调函数设置ref:
class MyComponent extends React.Component {
setTextInputRef = (element) => {
this.textInput = element;
};
render() {
return <input ref={this.setTextInputRef} />;
}
}
Ref转发
使用React.forwardRef将ref传递给子组件:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// 父组件可以获取button的ref
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
注意事项
Ref不应过度使用,应优先考虑React的数据流。仅在需要直接操作DOM或访问组件实例时使用。函数组件内部不能直接使用ref属性,必须通过forwardRef或useImperativeHandle处理。






