【问题标题】:How can I get the height of the wrapper after rendering the child?渲染孩子后如何获得包装器的高度?
【发布时间】:2019-07-16 15:54:22
【问题描述】:

我有一个组件网格,我需要在渲染他的孩子后得到他的高度。 children是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

【问题讨论】:

  • 定义“慢得多”。组件是异步加载数据还是在初始渲染后同步执行其他操作?也许使用useLayoutEffect 而不是useEffect 可以解决您的问题。
  • @Chris,在网格渲染和拉伸网格后加载的孩子 - 是一个简单的 div
  • 以下是否解决了您的问题?

标签: reactjs render children ref


【解决方案1】:

问题是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>

【讨论】:

  • 你能告诉我没有 React hooks 的替代方案吗?这会很有帮助。
猜你喜欢
  • 2017-05-21
  • 2021-12-09
  • 1970-01-01
  • 2018-04-28
  • 2022-11-22
  • 2023-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多