我正在构建一个动态图像网格,并尝试找到每个图像的实际高度(以像素为单位),以相应地调整布局。
我的问题是当尝试访问未定义的ref.current.clientHeight时。我试着关注这篇文章的How can I use multiple refs for an array of elements with hooks?,但无法访问图像的高度
const Grid = ({ arr }) => {
const ref = useRef([])
const arrLength = arr.length;
const [elRefs, setElRefs] = useState([])
useEffect(()=> {
setElRefs(elRefs => (
Array(arrLength).fill().map((_, i) => elRefs[i] || createRef())
));
},[arrLength])
return (
<Container>
{arr && arr.length !== 0 ? arr.map((o, i) => {
// I want to access the clientHeight here to pass to the GridCard component as a prop
return (
<GridCard
key={i}
data={o}
width={"280px"}
height={"auto"}
ref={elRefs[i]}
>
</GridCard>
)
}) : null}
</Container>
);
}
export default Grid;发布于 2021-08-10 22:14:50
请看一下react-use-measure包。
示例用法:
const [ref, bounds] = useMeasure({ polyfill: ResizeObserver });
return (
<Grid
container
ref={ref}
className={clsx(classes.root, bounds.width <= 300 ? classes.narrow : undefined)}
...https://stackoverflow.com/questions/68733706
复制相似问题