reactjs - 获取与窗口相关的元素顶部偏移量

标签 reactjs typescript react-hooks next.js

我正在尝试实现将返回元素的 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/

相关文章:

javascript - 在 typescript 中导入文件的正确方法是什么?

typescript - 如何在 TypeScript 中声明仅包含对象而不包含函数的类型

typescript - "... resolves to a non-module entity and cannot be imported using this construct"是什么意思?

reactjs - React Hook "useEffect"被有条件地调用。 React Hooks 必须在每个组件渲染中以完全相同的顺序调用

javascript - 让 React 与 math.js 库一起工作

javascript - React - 在组件内动态创建列表项

javascript - 为什么我可以在 React 中省略带括号的 return 语句

typescript - 如何在每个文件的基础上选择加入 TypeScript 的 strictPropertyInitialization?

javascript - 如何在 react 中创建全局数组?当我对每个索引进行单独的操作时,我希望它们将它们保存在一个数组中

reactjs - React TODO 示例中的dispatcherIndex 用于什么