TypeError: Cannot read property 'offsetHeight' of null after screen resize when using React.createRef

TypeError: Cannot read property 'offsetHeight' of null after screen resize when using React.createRef

我正在尝试为下面的每个 StyledSlide 样式组件附加一个引用,然后测量每个组件的 offsetHeight 以确定哪张幻灯片最高。

下面我用的是React.createRef。这对于初始渲染几乎可以正常工作,但是当我调整浏览器大小时出现以下错误:

Uncaught TypeError: Cannot read property 'offsetHeight' of null

如果我执行 console.log(this.refArray),我仍然可以看到每个引用并在控制台中找到 offsetHeight

我想做的是调整大小以重新计算最高的幻灯片。

以下是相关主要部分的伪示例:

class CarouselComponent extends React.Component {
  constructor(props) {
    super(props);
    this.refArray = [];
  }

  handleResize = () => {
    let highestSlide = 0;

    this.refArray.forEach(ref => {
      if (highestSlide < ref.current.offsetHeight) {
        highestSlide = ref.current.offsetHeight;
      }
    });
    console.log(`highest slide: ${highestSlide}`);
    console.log(this.refArray);
  };

  componentDidMount() {
    this.handleResize();
    window.addEventListener("resize", this.handleResize);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.handleResize);
  }

  getAllSlides = () => {
    const { collectionOfSlides } = this.props;

    return collectionOfSlides.map((component, index) => {
      const slideHeightRef = React.createRef();
      this.refArray.push(slideHeightRef);
      return (
        <StyledSlide key={index} innerRef={slideHeightRef}>
          {React.cloneElement(component)}
        </StyledSlide>
      );
    });
  };

  render() {
    return <div>{this.getSlides()}</div>;
  }
}

如有任何关于最佳前进方向的建议,我们将不胜感激!或者如何最好地解决这个问题

调整大小事件可能会在您的元素呈现之前触发。只需添加一个额外的条件:

  handleResize = () => {
    let highestSlide = 0;

    this.refArray.forEach(ref => {
      if (ref.current && highestSlide < ref.current.offsetHeight) {
        highestSlide = ref.current.offsetHeight;
      }
    });
  };