【问题标题】:React: how to calculate the height of a div based on its width?React:如何根据宽度计算 div 的高度?
【发布时间】:2022-10-18 18:00:01
【问题描述】:

我必须根据它的宽度找到一个 div 的高度。

这是我的尝试:

import React from 'react';
import Image from "next/image";
import DivHeightfromWidth from "src/components/Dimension/divheight.jsx";

const GalleryTab = ({ image }) => {
    const targetRef = React.useRef(null);
    const calcHeight = DivHeightfromWidth(targetRef, 11);

    return <div ref={targetRef} style={{ height: calcHeight, width: "100%" }}>
        <Image
            src={image.src}
            alt={image?.alt}
            layout='fill'
            objectFit='contain'
        />
    </div> 
}
export default GalleryTab;

我为我的 div 设置了 ref (targetRef) 并调用 DivHeightfromWidth 函数。

这是设置new Observer 的位置:

import React from "react";

const DivHeightfromWidth = (elRef, ratio) => {
    const [width, setWidth] = React.useState(0);
    var height = 0;

    const observer = React.useRef(
        new ResizeObserver(entries => {
            // Only care about the first element, we expect one element ot be watched
            const { width } = entries[0].contentRect;

            setWidth(width)

        })
    );

    React.useEffect(() => {
        if (elRef != null && elRef.current) {
            if (observer != null && observer.current) {
                observer.current.observe(elRef.current);
                if (observer.current.observe(elRef.current) != null) {
                    return () => {
                        observer.current.unobserve(elRef.current);
                    };
                }

            }

        }

    }, [elRef, observer]);

    if (ratio === 169)
        height = width * 16 / 9;
    else
        height = width;

    return height;
}

export default DivHeightfromWidth;

我收到此错误:ResizeObserver is not defined。

此外,我尝试在GalleryTab 中将useEffect 用于calcHeight,但出现了不同的错误:Invalid hook call. Hooks can only be called inside of the body of a function component。

您对如何使其工作有任何想法吗?

【问题讨论】:

    标签: reactjs react-hooks next.js observers


    【解决方案1】:

    这是我在useEffect 钩子中使用ref 的clientWidth 的简单解决方案:

    const GalleryTab = ({ image }) => {
        const [height, setHeight] = React.useState(0)
        const ref = React.useRef([])
    
        React.useEffect(() => {
            setHeight(ref.current[0].clientWidth)
        }, [])
    
        return <div ref={ref} style={{ height: height, width: "100%" }}>
            <Image
                src={image.src}
                alt={image?.alt}
                layout='fill'
                objectFit='contain'
            />
        </div> 
    }
    export default GalleryTab;
    

    当你做setHeight时,你可以计算任何比率,在这种情况下是1:1所以width和height具有相同的维度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 2017-02-23
      相关资源
      最近更新 更多