typeError:无法在“ResizeObserver”上执行“observe”:参数 1 不是“Element”类型

Kis*_*sho 4 javascript reactjs gatsby

为了解释上下文,我正在为盖茨比项目构建一个 Instagram 轮播。轮播中的图像通过以下方式显示

                  {data.allInstaNode.edges.map((image) => (
                        <Background
                            src={image.node.localFile.childImageSharp.fluid}
                            className="img-fluid"
                            height="38vh"
                            width="100%"
                        />
                    ))}
Run Code Online (Sandbox Code Playgroud)

渲染图像的背景组件使用 Gatsby 背景图像,如下所示

import React from 'react';
import BackgroundImage from 'gatsby-background-image';

export default function Background(props) {
    return (
        <BackgroundImage
            xs={props.xs}
            sm={props.sm}
            md={props.md}
            lg={props.lg}
            fluid={props.src}
            style={{ height: `${props.height}`, width: `${props.width}`, margin: '1rem' }}
        >
            {props.children}
        </BackgroundImage>
    );
}
Run Code Online (Sandbox Code Playgroud)

这个问题是这个内容过去渲染得很好,现在不这样做,因为它给了我这个错误 - TypeError: 无法在“ResizeObserver”上执行“observe”:参数 1 不是“Element”类型。

我做了一些搜索来解决这个问题,并发现了这个解决方案,它似乎很有希望,但对我来说不是很清楚 - https://github.com/souporserious/react-measure/issues/76

有人可以帮忙吗?:)

Col*_*lin 5

发生这种情况是因为当您尝试引用该元素时该元素尚不存在。

您可以使用setTimeout(() => { yourCode },100)so 它将在尝试访问 dom 元素之前等待 100ms,或者您可以使用

await waitUntil(() => myDomElement != null, { timeout: 20000 });
.... <your code> 
Run Code Online (Sandbox Code Playgroud)

这将在运行代码之前等待您的元素不为空(上面的代码将等待最多 20 秒,超时以毫秒为单位)