react无限滚动_如何使用React和CSS Grid构建无限滚动图片库

news/2024/7/7 5:47:14

react无限滚动

介绍 (Introduction)

In this tutorial, we will use the React frontend Javascript framework and CSS Grid to build an infinite scroll image gallery, using the Unsplash API to embed the photographic images. Using a codepen coding challenge from Scotch.io as a base for our code, we will use React.js to build out the interface, Axios to make the HTTP requests, and the react-infinite-scroll library to implement the infinite scroll feature.

在本教程中,我们将使用React前端Javascript框架和CSS Grid通过Unsplash API嵌入照片图像来构建无限滚动图像库。 使用来自Scotch.io的codepen编码挑战作为我们代码的基础,我们将使用React.js来构建接口,使用Axios来发出HTTP请求,并使用react-infinite-scroll库来实现无限滚动功能。

Also, for this tutorial, we’ll employ React Hooks and use functional components throughout the project.

另外,在本教程中,我们将使用React Hooks并在整个项目中使用功能组件。

先决条件 (Prerequisites)

For this tutorial, use this Image Collage Base code as your starting point to build your project upon.

对于本教程,请使用此Image Collage Base代码作为构建项目的起点。

步骤1 —安装所需的软件包 (Step 1 — Installing Required Packages)

Import all required dependencies from a CDN. Codepen provides a search bar with which you can type in the name of the module, then select one from the result and add it to your project.

从CDN导入所有必需的依赖项。 Codepen提供了一个搜索栏,您可以使用其输入模块名称,然后从结果中选择一个并将其添加到您的项目中。

Dependencies installed are:

安装的依赖项是:

  • React

    React

  • React-DOM

    ReactDOM

  • React-Infinite-Scroll-Component

    React无限滚动组件

  • Axios

    Axios

Go on to Unsplash to create an application and obtained an access key.

继续到Unsplash创建一个应用程序并获取访问密钥。

第2步-构建基础组件 (Step 2 — Building the Base Component)

In React, the HTML template for the parent component is written in JSX. We shall proceed to write these HTML elements that make the template in JSX.

在React中,父组件HTML模板是用JSX编写的。 我们将继续在JSX中编写构成模板的这些HTML元素。

Create a functional component and render on the DOM with:

创建一个功能组件,并使用以下命令在DOM上呈现:

let Collage = () => {

    // Return JSX
  return (
    <div className="hero is-fullheight is-bold is-info">
      <div className="hero-body">
        <div className="container">
          <div className="header content">
            <h2 className="subtitle is-6">Code Challenge #16</h2>
            <h1 className="title is-1">
              Infinite Scroll Unsplash Code Challenge
            </h1>
          </div>
    // Images go here

        </div>
      </div>
    </div>
  );
};

// Render the component to the DOM element with ID of root
ReactDOM.render(<Collage />, document.getElementById("root"));

Here, you created the parent component Collage , returned the HTML elements in JSX, and rendered it in the DOM element with an ID of root. Bulma classes were used to provide basic styling of the page.

在这里,您创建了父组件Collage ,返回了JSX中HTML元素,并将其呈现在ID为root的DOM元素中。 Bulma类用于提供页面的基本样式。

步骤3 —构建单个图像组件 (Step 3 — Building a Single Image Component)

Next, let’s move on to creating a single component for a single fetched image. This will help us set the position of each image.

接下来,让我们继续为单个获取的图像创建单个组件。 这将帮助我们设置每个图像的位置。

Create a single functional component with:

使用以下方法创建单个功能组件:

const UnsplashImage = ({ url, key }) => (
  <div className="image-item" key={key} >
    <img src={url} />
  </div>
);

This component receives props of url and key, which are the URL of the image to be displayed and the key for each rendered image. In the component, we use the <img/> element to display the fetched image.

此组件接收urlkeyurl ,这是要显示的图像的URL和每个渲染图像的密钥。 在组件中,我们使用<img/>元素显示获取的图像。

步骤4 —从Unsplash获取和渲染随机图像 (Step 4 — Fetching and Rendering Random Images from Unsplash)

Unsplash provides a free API to fetch random images. The images will be stored in a state container and passed to the DOM from state. Since we’ll use React Hooks, we’ll handle state and lifecycle methods with useState and useEffect, respectively.

Unsplash提供免费的API来获取随机图像。 图像将存储在状态容器中,并从状态传递到DOM。 由于我们将使用React Hooks,因此我们将分别使用useStateuseEffect处理状态和生命周期方法。

In the Collage component, create two state variables, one to hold the incoming images and the other to store a boolean that tells the program if the images are loaded or not.

Collage组件中,创建两个状态变量,一个用于保存传入的图像,另一个用于存储一个布尔值,该布尔值告诉程序是否加载了图像。

[...]

const [images, setImages] = React.useState([]);
const [loaded, setIsLoaded] = React.useState(false);

[...]

Next, we’ll create a function that fetches 10 random images using Axios. This is done by making a GET request to the API endpoint while passing your obtained access key and the amount of images you want returned. Do this with:

接下来,我们将创建一个使用Axios获取10个随机图像的函数。 这是通过向API端点发出GET请求,同时传递获得的访问密钥和要返回的图像数量来完成的。 使用以下方法执行此操作:

const fetchImages = (count = 10) => {
    const apiRoot = "https://api.unsplash.com";
    const accessKey = "{input access key here}";

    axios
      .get(`${apiRoot}/photos/random?client_id=${accessKey}&count=${count}`)
      .then (res => {
        setImages([...images, ...res.data]);
        setIsLoaded(true);
      });
};

Axios is a promise-based library, and on the resolution of the request, we use the setImages method to fill in the images fetched, as well as spread any previous images fetched. Also, we set the value of loaded to true.

Axios是一个基于Promise的库,根据请求的分辨率,我们使用setImages方法填充获取的图像,并传播所有先前获取的图像。 另外,我们将loaded的值设置为true

Now that we have images stored in state, let’s call this fetchImages function once the component is mounted. In earlier versions of React, we would do this with the componentDidMount lifecycle method. However, React now provides the useEffect hook to handle all lifecycle operations in a functional component.

现在我们已经将图像存储在状态中,一旦组件被安装,就让我们调用此fetchImages函数。 在React的早期版本中,我们将使用componentDidMount生命周期方法进行此操作。 但是,React现在提供useEffect钩子来处理功能组件中的所有生命周期操作。

In the Collage component, call fetchImages on mount with:

Collage组件中,使用以下fetchImages在安装时调用fetchImages

[...]

React.useEffect(() => {
    fetchImages();
}, []);

[...]

The useEffect hook takes a second parameter, which is an array. The provided function in the hook will run every time the array is updated or modified.

useEffect挂钩具有第二个参数,它是一个数组。 挂钩中提供的函数将在每次更新或修改阵列时运行。

Now you have a page that fetches ten random images from Unsplash. Let’s proceed to render the images in an infinite scroll container.

现在您有了一个页面,可以从Unsplash获取10个随机图像。 让我们继续在无限滚动容器中渲染图像。

React-infinite-scroll-component provides the ability to display a loading spinner or any element as a placeholder, call a function to fetch more data once the loader is in view or approaches view, and displays any specified data. In the returned JSX of Collage and after the div with a class of header, render the images in the infinite scroll component with:

React-infinite-scroll-component提供以下功能:显示加载微调框或任何元素作为占位符,调用函数以在加载器处于视图或接近视图时获取更多数据,并显示任何指定的数据。 在返回的Collage JSX中,以及在带有一类headerdiv之后,使用以下命令在无限滚动组件中渲染图像:

<InfiniteScroll
     dataLength={images}
     next={() => fetchImages(5)}
     hasMore={true}
     loader={
      <img
         src="https://res.cloudinary.com/chuloo/image/upload/v1550093026/scotch-logo-gif_jq4tgr.gif"
         alt="loading"
      />}
 >
     <div className="image-grid" style={{ marginTop: "30px" }}>
        {loaded ? 
            images.map((image, index) => (
                <UnsplashImage url={image.urls.regular} key={index} />
            )): ""}
    </div>
</InfiniteScroll>

In the InfiniteScroll component, we passed a function to the next parameter. The function calls the fetchImages function and passes a parameter of 5, which is the number of images to be fetched. In the loader parameter, we passed an image in JSX to serve as the loading placeholder.

InfiniteScroll组件中,我们将一个函数传递给next参数。 该函数调用fetchImages函数并传递参数5 ,这是要获取的图像数。 在loader参数中,我们在JSX中传递了一个图像作为加载占位符。

.map() is used to iterate through the images array in state and renders each image using the UnsplashImage component.

.map()用于迭代状态下的images数组,并使用UnsplashImage组件渲染每个图像。

We’ll use CSS grid to style the images fetched. Edit the CSS to this:

我们将使用CSS网格对获取的图像进行样式设置。 将CSS编辑为:

.title {
  font-family: 'Carter One';
}
.container {
  margin-top: 50px;
  text-align: center;
}

.image-grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  grid-auto-rows: minmax(50px, auto);

  .image-item:nth-child(5n){
    grid-column-end: span 2;
  }

  img{
    display: flex;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

This creates a grid with columns with a width of 250px and fills the entire image container. Also, the rows are set to have a minimum of 50px and a maximum of auto to fit each image. We used the grid-column-end property on every fifth image to make it take up two image spaces instead of one.

这将创建一个具有250px宽度的列的网格,并填充整个图像容器。 此外,行设置为最小为50px,最大为auto以适合每个图像。 我们在每五张图像上使用grid-column-end属性,使其占据两个图像空间而不是一个。

The object-fit property ensures each image fits or contains the full size of its container.

object-fit属性可确保每个图像都适合或包含其容器的完整大小。

You can find the completed gallery here https://codepen.io/Chuloo/full/BMPXqy.

您可以在这里https://codepen.io/Chuloo/full/BMPXqy中找到完整的画廊。

结论 (Conclusion)

In this tutorial, we built out an image gallery using React hooks, as well as using CSS grid. You can try to play around with the grid to create an even better setup.

在本教程中,我们使用React钩子以及CSS网格构建了一个图片库。 您可以尝试使用网格来创建更好的设置。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-build-an-infinite-scroll-image-gallery-with-react-css-grid-and-unsplash

react无限滚动


http://www.niftyadmin.cn/n/3649496.html

相关文章

[Domino]Tomcat需要NCSO.jar来定位Domino异常

[Domino]Tomcat需要NCSO.jar来定位Domino异常编写者日期关键词郑昀ultrapower2005-6-15Java Tomcat Axis NotesFactory我试图从Web Service访问Domino。Web Service的构建方法是&#xff1a;AxisTomcat&#xff0c;在Eclipse中加入了tomcatPluginV31beta插件&#xff0c;从而很…

初识Java设计模式

设计模式简介 设计模式(Design pattern)代表了最佳的实践&#xff0c;通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。设计模式是…

如何在Ubuntu 18.04上使用Ansible获取让我们加密证书

The author selected the Electronic Frontier Foundation to receive a donation as part of the Write for DOnations program. 作者选择了电子前沿基金会来接受捐款&#xff0c;这是Write for DOnations计划的一部分。 介绍 (Introduction) Modern infrastructure manageme…

如何在一个没有root权限的Android设备上创建一个SOCKS代理(英文转载)

How to Setup a SOCKS Proxy for Android Without Root原网址&#xff1a;http://www.devineloper.com/2013/08/28/setup-socks-proxy-android-without-root/ As the number of mobile Internet-connected devices continues to rise, so does the number of public-WiFi acces…

用自己的手机调试Android应用程序——Android Studio

最近在学习Android应用开发&#xff0c;一般来说都是用AVD建立的虚拟手机来调试和运行Android应用程序。不过自己的手机也是Android的&#xff0c;所以就是尝试用自己的手机来调试程序。不过在调试之前先做好手机的重要数据备份&#xff0c;因为有时候可能自己写的程序有BUG或者…

Angular-cli卸载以后安装指定版本

由于我的J2EE前端使用的是Angular 8.3.18。而Angular默认安装的是9.0以上的版本。这样在项目启动的时候会一直提示Angular版本不匹配。而且9.0的有些时候不太稳定。所以就想卸载重新安装指定版本。以下操作在CMD窗口运行。 卸载 1、卸载之前的版本 npm uninstall -g angular/cl…

Android开发必备的国内外网站、博客、论坛

Android现在是一个非常流行的移动操作系统。这个小小机器人创建一个大大的世界。许多开发商也致力于Android开发。对于新手和专家&#xff0c;你都要保持你技术储备的更新&#xff0c;知道在Android社区中的最新头条。所以我们推荐一些值得开发人员收藏的Android相关的网站&…