Реагировать на интеграцию lightgallery.js без JQuery? - PullRequest
0 голосов
/ 12 мая 2019

Я искал подходящее руководство для интеграции библиотеки lightgallery.js в мое приложение, но через несколько часов я не нашел никаких решений. Поскольку я использую React, я не хочу смешивать его с JQuery.

Я наткнулся на множество похожих вопросов, таких как на этот , но, поскольку все они используют JQuery, я не могу использовать их решения.

Кроме того, я обнаружил пакет реагировать-lightgallery (обертка React для lightgallery.js), но он пока не поддерживает видео.

В документации lightgallery.js есть руководство по установке. После выполнения всех шагов, импорта lightgallery.js и попытки его распечатать (как предложено здесь владельцем библиотеки), отображается пустой объект.

Что было бы лучшим решением для этого? Есть ли хорошие альтернативы?

Спасибо!

Ответы [ 2 ]

0 голосов
/ 28 июня 2019

Вот рабочий пример с cloudinary на Cloudinary LightGallery

Код для Cloundinary LightGallery React Component с использованием Styled Components и styless css приведен ниже.

Код для компонента загрузки находится в моем репозитории GitHub по адресу.

UploadWidget

/* eslint-disable indent */
import React, { Component, Fragment } from 'react'
import { LightgalleryProvider, LightgalleryItem } from 'react-lightgallery'
import axios from 'axios'
import styled from 'styled-components'
import { CloudinaryContext, Transformation, Image } from 'cloudinary-react'
import { Grid, Cell } from 'styled-css-grid'
import { media } from '../../utils/mediaQuery'
import 'lightgallery.js/dist/css/lightgallery.css'

import 'lg-autoplay.js'

 const SectionTitle = styled.h3`
   font-size: 1em;
   margin: 0.67em 0;
   ${media.xs`
     font-size: .85em;
   `}
 `
class Gallery extends Component {
  constructor (props) {
    super(props)
    this.link = React.createRef()
    this.state = {
      gallery: [],
      isOpen: false,
      link: this.href,
    }
  }

 componentDidMount () {
    // Request for images tagged cats
   axios.get('https://res.cloudinary.com/mansbooks/image/list/v1557911334/cats.json')
     .then(res => {
       console.log(res.data.resources)
       this.setState({ gallery: res.data.resources })
     })
 }
 onLink (event) {
   this.setState({ link: this.href = 
   `https://res.cloudinary.com/mansbooks/image/upload/${data.public_id}.jpg` })
 }
 uploadWidget () {
   let _this = this
   cloudinary.openUploadWidget({ cloud_name: 'mansbooks', upload_preset: 'photos- 
   preset', tags: ['cats'], sources: ['local', 'url', 'camera', 'image_search', 
   'facebook', 'dropbox', 'instagram'], dropboxAppKey: 'Your API Key', googleApiKey: 
   'Your API Key' },
      function (error, result) {
      // Update gallery state with newly uploaded image
          _this.setState({ gallery: _this.state.gallery.concat(result) })
      })
  }
  render () {

return (
  <div>
    <Fragment>
      <SectionTitle>Gallery by Cloudinary</SectionTitle>
      <div>
        <CloudinaryContext cloudName='mansbooks'>
          <Grid columns='repeat(auto-fit,minmax(260px,1fr))' id='hash'>
            <LightgalleryProvider>
              {
            this.state.gallery.map(data => {
            return (
              <Cell key={data.public_id}>
                <LightgalleryItem group='group1' src={`https://res.cloudinary.com/mansbooks/image/upload/${data.public_id}.jpg`} data-sub-html={'data.public_id'}>
                  <Image publicId={data.public_id} onClick={() => this.setState({ isOpen: true })}>
                    <Transformation
                      crop='scale'
                      width='250'
                      height='170'
                      radius='6'
                      dpr='auto'
                      fetchFormat='auto'
                      responsive_placeholder='blank'
                    />
                  </Image>
                </LightgalleryItem>
              </Cell>
              )
            })
          }
            </LightgalleryProvider>
          </Grid>
        </CloudinaryContext>
      </div>
    </Fragment>
  </div>
)
}
}

export default Gallery
0 голосов
/ 09 июня 2019

Я справился с этим так.Может быть, это не полная и лучшая практика, но она дает вам общее представление о том, как с этим справиться

import React, { PureComponent } from "react";
import Gallery from "lightgallery.js";

import "lightgallery.js/dist/css/lightgallery.min.css";

class _Gallery extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    let self = this;
    this.gallery = document.getElementById("lightgallery");
    lightGallery(this.gallery, {
      dynamic: true,
      dynamicEl: [
        {
          src:
            "1.jpg",
          thumb: "1.jpg",
          subHtml:
            "<h4>Fading Light</h4><p>Classic view</p>"
        },
        {
          src:
            "2.jpg",
          thumb: "2.jpg",
          subHtml:
            "<h4>Bowness Bay</h4><p>A beautiful Sunrise</p>"
        },
        {
          src:
            "3.jpg",
          thumb: "3.jpg",
          subHtml: "<h4>Coniston Calmness</h4><p>Beautiful morning</p>"
        }
      ]
    });

    this.gallery.addEventListener("onCloseAfter", function(event) {
      window.lgData[self.gallery.getAttribute("lg-uid")].destroy(true);
      self.props.onCloseGallery();
    });
  }

  render() {
    return <div id="lightgallery" />;
  }
}

export default _Gallery;
...