【问题标题】:Get height of component after render completion渲染完成后获取组件高度
【发布时间】:2023-02-22 04:46:31
【问题描述】:

只有在完成渲染后,我才尝试获取 SelectedCard 组件的高度。 最多可以有 3 个,并试图获取 3 个之间的最高值。

虽然它仍在渲染,但我只是展示了一些闪烁的效果。

问题是,height 值出现不一致。

在我正在尝试的示例中,正确的值应该是 160,并且它在大约 50% 的时间内有效。我只是尝试使用 1 个 SelectedCard 组件,甚至不是 3 个。

但是我间歇性地看到值 39 和 85 而不是 height 的 160。相信它是在微光效果期间捕获值,而 85 可能是在中间渲染期间。

如何确保等待并始终获得 160 的高度值?

我尝试使用 useEffect 和相同的结果。

尝试在 useEffect 中也使用超时等待 6 秒,这现在一直有效。

  useLayoutEffect(() => {
    setTimeout(() => {
      let height = 0;
      setMinHeight(height);
      cardRefs.current.forEach(ref => {
        if (ref) {
          height = Math.max(height, ref.clientHeight);
        }
      });
      console.log(`ktest: maxHeight: ${height}`)
      setMinHeight(height);
    }, 6000)
  }, [comparedCardsData, numberOfColumns]);

但它会产生不良影响,即某些样式会在 6 秒后突然发生变化。
此外,我不希望随机插入 6 秒之类的等待时间。对于某些网络延迟,即使 6 秒也可能不够。

这里有什么问题,我可以得到一些帮助吗?

我希望不使用超时并能够获得一致的高度值。

import React, {useLayoutEffect, useRef, useState,} from 'react';
import {compose} from 'redux';
import {connect} from 'react-redux';
import SelectedCard from './SelectedCard';
import {createStructuredSelector} from "reselect";

const Header1 = ({
    data,
    numberOfColumns,
  }) => {
  const [minHeight, setMinHeight] = useState(0);
  const cardRefs = useRef([]);

  useLayoutEffect(() => {
    let height = 0;
    cardRefs.current.forEach(ref => {
      if (ref) {
        height = Math.max(height, ref.clientHeight);
      }
    });
    console.log(`height: ${height}`) // differs intermittently.
    setMinHeight(height);
  }, [data, numberOfColumns]);

  return data.slice(0, numberOfColumns)
    .map((card, index) => {
      return (
        <div>
          <div ref={ref => cardRefs.current[index] = ref} style={{minHeight}}>
            <SelectedCard/>
          </div>
          {/* many other components */}
        </div>
      );
    });
};

const mapStateToProps = createStructuredSelector({
  .....
});

const mapDispatchToProps = {
  .....
};

const all = compose(
  connect(mapStateToProps, mapDispatchToProps)
);

export default all(Header1);

【问题讨论】:

  • 首先对组件进行渲染,但确保它从视图中隐藏但不显示。在第一个 ender 获得高度之后
  • @SteveTomlin 正在寻找一种等待渲染完成的方法。我不想使用超时。
  • 使用componentDidMount()方法怎么样?它在渲染组件后调用。 Check out this thread here.
  • @ImtiazRaqib 我正在使用功能组件。这与不提供所需结果的 useEffect 挂钩的工作方式相同。
  • 从您的代码 sn-p 此处不清楚是什么负责改变您的大小的渐进式渲染。如果这是样式表加载,那么也许您最好将应用程序的加载延迟到它们加载之后。如果它是图像,您最好让组件不可见,直到它们的 onload 事件触发。您能否更深入地了解 SelectedCard 组件的内容?

标签: javascript reactjs


【解决方案1】:

安装后获取高度的示例


const Table = ({onMount}) => {
  const ref = useRef()
  useEffect(() => {
      const height = window.getComputedStyle(ref.current).getPropertyValue("height");
      onMount(height);
    }
  }, [ref, onMount]);

return (<div ref={ref}>whatever</div>)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    相关资源
    最近更新 更多