React中获取DOM
在 React 组件中获取/操作 DOM,需要使用 useRef React Hook钩子函数,分为两步:
- 使用useRef创建 ref 对象,并与 JSX 绑定
image.png
- 在DOM可用时,通过 inputRef.current 拿到 DOM 对象
image.png
ref操作子组件
要想操作子组件,需要用
forwardRef包住子组件函数,并且用useImperativeHandle暴露子组件的属性和方法。
import { forwardRef, useState, useImperativeHandle, useRef } from 'react';
const Son = forwardRef((props, ref) => {
const [count] = useState(0);
const inputRef = useRef(null);
const handleClick = () => {
console.log('click');
};
const focus = () => {
inputRef.current.focus();
};
// 相当于vue3中的defineExpose
useImperativeHandle(ref, () => {
return {
handleClick,
focus,
count,
};
}, [count]);
return <input ref={inputRef} />;
});
const App = () => {
const sonRef = useRef(null);
const handleShowSonRef = () => {
console.log('sonRef count', sonRef.current.count);
sonRef.current.focus();
};
return (
<div>
<div>
<button onClick={handleShowSonRef}>show sonRef</button>
</div>
<Son ref={sonRef} />
</div>
);
};
export default App;









网友评论