我正在尝试实现将返回元素的 offsetTop 的钩子(Hook)。这是将一些样式应用于它粘在顶部的标题所必需的。
import { useState, useEffect } from 'react';
interface ElementPosition {
left: number | undefined;
right: number | undefined;
top: number | undefined;
bottom: number | undefined;
}
export const useElementPosition = (ref: any): ElementPosition => {
const [position, setPosition] = useState<ElementPosition>({
left: undefined,
right: undefined,
top: undefined,
bottom: undefined,
});
useEffect(() => {
if (ref.current) {
setPosition({
top: ref.current.offsetTop,
bottom: ref.current.offsetBottom,
left: ref.current.offsetLeft,
right: ref.current.offsetRight,
});
}
}, [ref.current]);
return position;
};
但现在我记起 ref.current
更改不会触发 useEffect,因此我只能获得初始偏移量。有什么方法可以像 hooks
一样以可重用的方式做到这一点吗?
最佳答案
对于这种情况,您可以使用 callback ref
反而。当 ref
附加到新节点时将调用回调。
export const useElementPosition = () => {
const [position, setPosition] = useState<ElementPosition>({
left: undefined,
right: undefined,
top: undefined,
bottom: undefined
});
const ref = useCallback((node) => {
if (node !== null) {
setPosition({
top: node.offsetTop,
bottom: node.offsetBottom,
left: node.offsetLeft,
right: node.offsetRight
});
}
}, []);
return [position, ref];
}
在这种情况下,您无需将 ref
传递给自定义 Hook ,而是返回 ref
以从中使用。
const PositionExample = () => {
const [position, ref] = useElementPosition();
console.log(position.top);
return (
<h1 ref={ref}>Hello world!</h1>
);
};
有关更多详细信息,请查看官方文档:React Hooks - How can I measure a DOM node? .
关于reactjs - 获取与窗口相关的元素顶部偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69356351/