【发布时间】:2021-11-20 04:16:38
【问题描述】:
我正在尝试实现将返回元素的 offsetTop 的钩子。这是需要将一些样式应用到它粘在顶部的标题。
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 这样以可重用的方式做到这一点?
【问题讨论】:
标签: reactjs typescript react-hooks next.js