javascript - 使用钩子(Hook)在调整大小时测量 React DOM 节点

标签 javascript reactjs react-hooks

我正在尝试测量窗口调整大小事件中的 React DOM 节点。我在 React hooks-faq 上使用了示例,但它只发生在第一次渲染时。如果我添加一个 useEffect 来监听调整大小,回调不会被调用?

function MeasureExample() {
    const [height, setHeight] = useState(0);

    const measuredRef = useCallback(node => {
        if (node !== null) {
            setHeight(node.getBoundingClientRect().height);
        }
    }, []);


    // Adding this effect doesn't re-calculate the height???
    useEffect(() => {

        window.addEventListener("resize", measuredRef);

        return (): void => {
            window.removeEventListener("resize", measuredRef);
        };

    }, [height])

    return (
        <>
            <h1 ref={measuredRef}>Hello, world</h1>
            <h2>The above header is {Math.round(height)}px tall</h2>
        </>
    );
}

最佳答案

这是另一种解决方案。

function MeasureExample() {
    const [height, setHeight] = useState(0);
    const [node, setNode] = useState(null);

    const measuredRef = useCallback(node => {
        if (node !== null) {
            setNode(node);
        }
    }, []);
    useLayoutEffect(() => {
        if(node){
         const measure = () => {
           setSize(node.getBoundingClientRect().height);
         }
        
         window.addEventListener("resize", measure );

         return () => {
           window.removeEventListener("resize", measure );
         };
       }
    }, [node])

    return (
        <>
            <h1 ref={measuredRef}>Hello, world</h1>
            <h2>The above header is {Math.round(height)}px tall</h2>
        </>
    );
}

关于javascript - 使用钩子(Hook)在调整大小时测量 React DOM 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58483197/

相关文章:

java - 根据时间从mysql中删除记录

javascript - Redux:如何将 action creators 编译成一个 action creators 表?

javascript - useState 对象数组

javascript - querySelectorAll,其中类不包含 'hide'

javascript - 从链接内的数据绑定(bind)中获取字符串

javascript - 如何使用 .filter() 从数组中删除值?

reactjs - 返回 JSX 的函数和类组件有什么区别?

javascript - 如何在 'useEffect' 钩子(Hook)中获取最新的组件变量值?

javascript - 单击事件后如何触发函数 useEffect?

javascript - 具有可变值的 Jquery 函数