【问题标题】:Get link of an image in react-photo-gallery?在 react-photo-gallery 中获取图像的链接?
【发布时间】:2018-03-18 16:47:00
【问题描述】:

我仍然是 reactJS 的初学者(使用 nodeJS 后端),我必须创建一个网站来管理我的收藏。我不知道我要问你的是否可行,但可能是。

所以我使用了一个 react 组件,react-photo-gallery。它是一个组件,您可以在其中使用 url 链接并将它们混合在一起以创建一个漂亮的画廊。

https://github.com/neptunian/react-photo-gallery

我正在使用 nodeJS 从数据库中获取信息,我从中获取所有图片的 url。例如,我有一组卡片,以及代表该集合的图像的 url。 我想要做的是获取我单击的图片的链接,以便我可以在另一个组件中使用它。

import React from 'react';
import { render } from 'react-dom';
import Gallery from 'react-photo-gallery';
import Photo from './Photo';


class PhotoGallery extends React.Component {
  constructor(props){
    super(props);
    this.onClick = this.onClick.bind(this);
    this.state = {
      urlImages: []
    };
  }
  async componentDidMount() {
    var getUrlImages = 'http://localhost:3004';
    const response = await fetch(getUrlImages+"/getUrlImages");
    const newList = await response.json();
    this.setState(previousState => ({
      ...previousState,
      urlImages: newList,
     }));
  }

  galleryPhotos() {
   if(this.state.urlImages) {
      return this.state.urlImages.map(function(urlimage) {
         return { src: urlimage.urlimage, width: 2, height: 2 }
      })
   }
}

  onClick() {
    alert(this.galleryPhotos().value);
  }

  render() {
    return (
      <Gallery axis={"xy"} photos={this.galleryPhotos()} onClick={this.onClick}/>
    )
  }
}
const photos = [];
export default PhotoGallery;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

基本上我想做的就是在onClick函数中获取图片的源链接。这可能吗?

提前致谢!

【问题讨论】:

    标签: node.js database image reactjs url


    【解决方案1】:

    检查onClick 事件。

    onClick(event) {
      alert(event.target.src)
    }
    

    DEMO

    【讨论】:

      【解决方案2】:

      Gallery 组件的 onClick 事件有多个参数:

      1. 事件
      2. 包含所选索引和原始照片对象的对象

      您可以在 onClick 处理程序中使用它:

      onClick(e, obj) {
        const src = obj.photo.src
        // do whatever you need with the src (setState, etc)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-12
        • 2016-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-29
        • 2020-05-12
        • 2016-04-20
        相关资源
        最近更新 更多