【发布时间】: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