[英]Components positions react dom
How do I use useRef to get the position of a component directly from the dom In this case I want to be able to get the position of the pageItem如何使用 useRef 直接从 dom 获取组件的 position 在这种情况下,我希望能够获取 pageItem 的 position
import React, { useState } from 'react'
import PageItem from '../components/pageItem'
const LandingPage = () => {
return (
<div className={classes.mainContainer}
>
<PageItem/>
</div>
)
}
If you have the ref you can use any element API like getBoundingClientRect
如果你有参考,你可以使用任何元素 API 像
getBoundingClientRect
const LandingPage = () => {
const divRef = useRef();
useEffect(() => {
console.log(divRef.current.getBoundingClientRect());
}, []);
return (
<div ref={divRef} className={classes.mainContainer}>
<PageItem />
</div>
);
};
You can't add ref to custom elements like您不能将 ref 添加到自定义元素,例如
<PageItem/>
You can wrap custom elements with default elements like div or send refs through props to child default elements您可以使用默认元素(如 div)包装自定义元素,或通过 props 将 refs 发送到子默认元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.