我有一个组件Grid,渲染孩子后需要得到他的身高。 儿童为100张图像,其渲染速度远低于Grid渲染速度。
import React, { FC, useEffect, useRef } from 'react'
import { TProps } from '.'
import { Grid, Wrap } from './contentStyle'
export const ContentComponent: FC<TProps> = ({
children,
}) => {
const grid = useRef<HTMLDivElement>(null)
useEffect(() => {
isPageBottom && getNextVideosPreviewAction({ pageNumber, video })
grid && grid.current && console.log('height', height && height.current.clientHeight)
})
return (
<Wrap>
<Grid ref={grid}>
{children}
</Grid>
</Wrap>
)
}
在控制台日志中-66,但在实际日志中-3006
答案 0 :(得分:0)
问题是useEffect
在渲染之后但在N张图像完全加载之前运行。您需要等待所有图像加载完毕,然后才能获得最终高度。
一种选择是在图像上使用onLoad
回调,并跟踪已加载了多少图像。如果所有图像都已加载,则该元素现在处于其完整高度,我们可以访问最终高度。
const App = () => {
const data = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
];
const parentEl = React.useRef(null);
const [loaded, updateLoaded] = React.useState(0);
const handleLoad = () => {
updateLoaded(loaded + 1);
}
React.useEffect(() => {
if (loaded === data.length) {
console.log('Height:', parentEl.current.clientHeight);
}
})
return (
<div ref={parentEl} >
{data.map(item => (
<img style={{width: 140}} onLoad={handleLoad} src={`https://via.placeholder.com/600x600?text=${item}`} />
))}
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0-alpha.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0-alpha.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>