如何在图片上实现悬停以从api显示更大的相同图片

时间:2019-08-01 09:19:06

标签: reactjs react-hooks

我已经能够使用react钩子和组件将照片从不飞溅的状态渲染到屏幕上。 接下来要实现的是将鼠标悬停在任何图像上,我会从api中获得更大尺寸的图像。

import React, { useState } from 'react';
import axios from 'axios';
import SearchBar from '../SearchBar/SearchBar';
import ImageList from '../ImageList/ImageList';
import './SearchPage.css';

const API_KEY = process.env.REACT_APP_ACCESS_KEY;

const SearchPage = () => {
  const [searchText, setSearchTerm] = useState('');
  const [image, setImage] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);

  const onInputChange = (e) => {
    setSearchTerm(e.target.value);
  };

  const fetchImages = () => {
    axios.get('https://api.unsplash.com/search/photos', {
      params: { query: searchText },
      headers: {
        Authorization: API_KEY,
      },
    })
      .then((data) => {
        setImage(data.data.results);
        setIsLoaded(false);
      });
  };

  const onSubmitHandler = (e) => {
    e.preventDefault();
    fetchImages();
    setIsLoaded(true);
  };

  return (
    <div>
      <SearchBar
        className="search-bar"
        onSubmitHandler={onSubmitHandler}
        onInputChange={onInputChange}
        searchText={searchText}
      />
      <div className="image-container">
        {image && <ImageList image={image} isLoaded={isLoaded} />}
      </div>
    </div>

  );
};
export default SearchPage;

import React from 'react';
import ReactLoading from 'react-loading';
import './ImageList.css';

const ImageList = ({ image, isLoaded }) => {
  if (isLoaded) {
    return (
      <div className="spinner">
        <ReactLoading type="spin" color="blue" />
      </div>
    );
  }

  const imgs = image.map(img => (
    <img
      key={img.id}
      src={img.urls.small}
    />

  ));

  if (imgs.length === 0) {
    return (
      <p>No images</p>
    );
  }
  return (
    <React.Fragment>
      {imgs}
    </React.Fragment>
  );
};

export default ImageList;

我将发布一些代码来显示。 所以基本上我想要的是,当我将鼠标悬停在img上时,应该在api上渲染一个更大的版本,供他下载,并可以显示照片的作者,并且可以单击以不打扰地转到原始图像

0 个答案:

没有答案