首页 > 解决方案 > react-images 为什么灯箱默认显示并失去其作为导入的样式

问题描述

我正在以这个 Codesandbox为起点。在这里您可以看到默认情况下灯箱是隐藏的,然后当您单击按钮时,它会打开灯箱,该灯箱位于其余内容上方的固定位置,具有透明的背景色。但是,当我尝试将其设置为另一个组件中的导入时,默认情况下灯箱是可见的,它也失去了它的样式,并且我没有看到关闭按钮。任何想法为什么会发生这种情况?

import React from "react";
import LB from "./LB";
import "./styles.css";

const photos = [
  {
    src: "https://source.unsplash.com/2ShvY8Lf6l0/800x599",
    width: 4,
    height: 3
  },
  {
    src: "https://source.unsplash.com/Dm-qxdynoEc/800x799",
    width: 1,
    height: 1
  },
  {
    src: "https://source.unsplash.com/qDkso9nvCg0/600x799",
    width: 3,
    height: 4
  },
  {
    src: "https://source.unsplash.com/iecJiKe_RNg/600x799",
    width: 3,
    height: 4
  },
  {
    src: "https://source.unsplash.com/epcsn8Ed8kY/600x799",
    width: 3,
    height: 4
  },
  {
    src: "https://source.unsplash.com/NQSWvyVRIJk/800x599",
    width: 4,
    height: 3
  },
  {
    src: "https://source.unsplash.com/zh7GEuORbUw/600x799",
    width: 3,
    height: 4
  },
  {
    src: "https://source.unsplash.com/PpOHJezOalU/800x599",
    width: 4,
    height: 3
  },
  {
    src: "https://source.unsplash.com/I1ASdgphUH4/800x599",
    width: 4,
    height: 3
  }
];

export default function App() {
  return <LB images={photos} />;
}

这是我迄今为止尝试过的更新的代码框(您也可以在其中看到默认情况下显示的灯箱而没有样式)

标签: reactjs

解决方案


我在此处查看您的代码在此处输入链接描述然后我搜索包 react-image,它的漂亮包,我实际上喜欢它,然后我将您的代码与npm 中的文档 react-images 进行比较,我认为您不需要将事件作为三个代码添加到灯箱:

   return (
      <ModalGateway>
        {modalIsOpen ? (
          <Modal onClose={this.toggleModal}>
            <Carousel views={images} />
          </Modal>
        ) : null}
      </ModalGateway>
    );

只需要给模块 onClose 函数和 Carousel 图像数组

实际上,我在我添加的 LB 组件文件中使用 ES6 重写了代码“老实说,我更喜欢箭头函数而不是绑定东西”

import React, { Component } from "react";
import Carousel, { Modal, ModalGateway } from "react-images";

class App extends Component {
  state = {
    currentImage: 0,
    modalIsOpen: false
  };
  openLightbox = () => {
    this.setState({
      currentImage: 0,
      modalIsOpen: true
    });
  };
  closeLightbox = () => {
    this.setState({
      currentImage: 0,
      modalIsOpen: false
    });
  };

  render() {
    return (
      <>
        <button onClick={this.openLightbox}>Open Lightbox</button>

        <ModalGateway>
          {this.state.modalIsOpen ? (
            <Modal onClose={this.closeLightbox}>
              <Carousel views={this.props.images} />
            </Modal>
          ) : null}
        </ModalGateway>
      </>
    );
  }
}

export default App;


推荐阅读