html中的对象react如何获取
React 中获取 DOM 对象的方法
在 React 中,可以通过 ref 来获取 DOM 对象或组件实例。以下是几种常见的方式:
使用 useRef Hook(函数组件推荐)

import { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
使用 createRef(类组件)
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
handleClick = () => {
this.inputRef.current.focus();
};
render() {
return (
<div>
<input ref={this.inputRef} type="text" />
<button onClick={this.handleClick}>Focus Input</button>
</div>
);
}
}
回调 Refs(适用于动态 ref 场景)

function MyComponent() {
let inputRef = null;
const handleClick = () => {
inputRef.focus();
};
return (
<div>
<input ref={el => inputRef = el} type="text" />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
获取子组件实例
通过 ref 也可以获取子组件的实例(仅限类组件):
class Child extends React.Component {
method() {
console.log('Child method called');
}
render() {
return <div>Child Component</div>;
}
}
class Parent extends React.Component {
childRef = React.createRef();
handleClick = () => {
this.childRef.current.method();
};
render() {
return (
<div>
<Child ref={this.childRef} />
<button onClick={this.handleClick}>Call Child Method</button>
</div>
);
}
}
转发 Refs(获取子组件 DOM)
使用 React.forwardRef 可以获取子组件内部的 DOM 元素:
const Child = React.forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
function Parent() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<Child ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
注意事项
- 函数组件默认不能直接通过
ref获取实例(除非使用forwardRef) ref不应过度使用,优先考虑 React 的状态驱动原则- 避免在渲染期间修改
ref.current,应在事件处理或副作用中操作






