reactjs - Pencereye göre elemanların üst offsetini al
Bir elementin offsetTop değerini döndürecek bir hook uygulamaya çalışıyorum. Bu, başlığın üstte sabit kalması için bazı stilleri uygulamak gerektiğinde gerekli.
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;
};
Ama şimdi hatırladım ki ref.current değişikliği useEffect'i tetiklemiyor, bu yüzden sadece başlangıç ofsetini alabiliyorum. Bunu hooks gibi yeniden kullanılabilir bir şekilde yapmanın bir yolu var mı?
Cevap #1
Bu senaryo için bunun yerine bir geri arama ref kullanabilirsiniz. Geri arama, ref yeni bir düğüme bağlandığında çağrılacaktır.
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];
}
Bu durumda, özel kancaya bir ref geçirmek yerine, kullanmak için ref'i ondan döndürürdünüz.
const PositionExample = () => {
const [position, ref] = useElementPosition();
console.log(position.top);
return (
<h1 ref={ref}>Hello world!</h1>
);
};
Daha fazla detay için resmi belgelere bakın: React Hooks - Bir DOM düğümünü nasıl ölçebilirim?
