单独功能中带有循环的Lightgallery.js渲染不起作用

时间:2018-10-23 22:06:02

标签: javascript node.js reactjs lightgallery

所以我正在一个React js项目中,我正在其中获取一个对象,其中包含一些细节,包括来自MySql数据库的图像名称(或更确切地说是本地路径)。我正在尝试使用LightGallery.js在图像滑块内显示对象的多个图像,就像lightgallery是其中之一。现在的问题:

如果我在render方法中使用了硬编码的html标签(现在已注释掉),则画廊的工作原理就像是一个吊饰。但是,我将需要动态渲染这些图像,因为我无法控制每个项目要上传多少图像。我试图编写returnPics()函数来推送所需的标签及其子元素(

这是必需的代码:

import React, { Component } from "react";
import Layout from "../components/Layout";
import axios from "axios";
import { Container, Header } from "semantic-ui-react";
import "lightgallery.js";

class item extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: "",
      title: "",
      category: "",
      description: "",
      owner: "",
      price: "",
      tags: [],
      pics: []
    };
  }

  async componentWillMount() {
    let thisObject;
    let pathname = window.location.pathname.split("/");
    let id = pathname[pathname.length - 1];

    let response = await axios.post(window.location.origin + "/item", { id });
    if (response.data.success) {
      thisObject = response.data.object;
      let picsTemp = [];

      for (let i = 0; i < response.data.pics.length; i++) {
        picsTemp.push(response.data.pics[i].name);
      }

      this.setState({
        id: response.data.id,
        title: thisObject[0].title,
        category: thisObject[0].category,
        description: thisObject[0].description,
        owner: thisObject[0].owner,
        price: thisObject[0].price,
        tags: response.data.tags,
        pics: picsTemp
      });
    }
  }

  returnPics = () => {
    let picsToReturn = [];

    for (let i = 0; i < this.state.pics.length; i++) {
      let source = "../static/" + this.state.pics[i];
      let key = "picObject" + i;
      let picKey = "pic" + i;
      let lgEvent = "&" + (i + 1);

      picsToReturn.push(
        <a key={key} href={source} lg-event-uid={lgEvent}>
          <img key={picKey} src={source} />
        </a>
      );
      console.log(picsToReturn);
    }
    return picsToReturn;
  };

  render() {
    return (
      <Layout>
        <Container textAlign="center">
          <Header size="huge">{this.state.title}</Header>

          <div id="lightgallery">
            {this.returnPics()}                               <------this doesn't

            {/* <a href="../static/Aere_adidas_f50.jpg">      <------this works
              <img src="../static/Aere_adidas_f50.jpg" />
            </a>
            <a href="../static/Aere_ps4.png">
              <img src="../static/Aere_ps4.png" />
            </a> */}


          </div>
          <script src="../node_modules/lightgallery.js/dist/js/lightgallery.min.js" />
        </Container>
        <script type="text/javascript">
          {lightGallery(document.getElementById("lightgallery"))};
        </script>
      </Layout>
    );
  }
}

export default item;

有人能弄清楚为什么会这样吗?

感谢您的帮助!

0 个答案:

没有答案