首页 > 解决方案 > 如何解决此“目标容器不是 DOM 元素”。在 React 与 React-Image Gallery/Lightbox 中?

问题描述

我试图找到一个解决方案来解决我对基于图像的画廊(例如灯箱或 FancyBox)的体验。遵循此文档并使用此代码作为示例 后出现此错误。

我尝试使用 react-images 无济于事,模态显示不正确,所以我尝试了链接 react-photo-gallery,我遇到了这个错误。我尝试将其转换为组件,但它与文件顶部的 App 功能不符。我还尝试在我的 pages 目录中创建一个 html 文件并将导入链接添加到 illustrationGallery 文件,但这似乎不起作用。

我的插图画廊文件

import React, { useState, useCallback } from "react";
import { render } from "react-dom";
import Gallery from "react-photo-gallery";
import Carousel, { Modal, ModalGateway } from "react-images";
import { illustrations } from "../components/illustrations";
import Artwork from '../pages/gallery';

function App() {
  const [currentImage, setCurrentImage] = useState(0);
  const [viewerIsOpen, setViewerIsOpen] = useState(false);

  const openLightbox = useCallback((event, { photo, index }) => {
    setCurrentImage(index);
    setViewerIsOpen(true);
  }, []);

  const closeLightbox = () => {
    setCurrentImage(0);
    setViewerIsOpen(false);
  };

        return (

            <div>
            <Gallery illustrations={illustrations} onClick={openLightbox} />
            <ModalGateway>
                {viewerIsOpen ? (
                <Modal onClose={closeLightbox}>
                    <Carousel
                    currentIndex={currentImage}
                    views={illustrations.map(x => ({
                        ...x,
                        srcset: x.srcSet,
                        caption: x.title
                    }))}
                    />
                </Modal>
                ) : null}
            </ModalGateway>
            </div>
        );
}
render(<App />, document.getElementById("illuGallery"));



本地主机窗口错误

invariant
node_modules/react-dom/cjs/react-dom.development.js:56
render
node_modules/react-dom/cjs/react-dom.development.js:21195
▲ 2 stack frames were expanded.
Module.<anonymous>
src/components/illustrationGallery.js:43
  40 |             </div>
  41 |         );
  42 | }
> 43 | render(<App />, document.getElementById("illuGallery"));
  44 | 

此错误描述位于顶部,但还有更多

只是试图使用反应来实现显示正确图像库的东西,使用另一个文档或从头开始会更容易吗?有没有人有任何建议或答案可以帮助?

标签: javascriptreactjslightbox

解决方案


发生这种情况是因为:

document.getElementById("illuGallery")找不到具有 id 的元素#illuGaller

如果你愿意让它工作,这是你真正想要对渲染做出反应的唯一组件。

代码沙盒项目为例。

你去你的模板,react 渲染元素。基本上index.htmlor template.html,在示例中是index.html

并确保反应所在的根元素将注入您的 JSX,确保它具有 idilluGallery


推荐阅读