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

本文教程展示了如何使用React前端框架和CSS Grid,结合Unsplash API,构建一个无限滚动的图片库。教程涵盖了从安装所需软件包到构建组件、获取和渲染随机图像、样式化库的全过程,并利用React Hooks简化状态管理和生命周期操作。
摘要由CSDN通过智能技术生成

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.iocodepen编码挑战作为我们代码的基础,我们将使用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:

安装的依赖项是:

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无限滚动

在HandsonTable的React组件中,如果你想要使得内部的竖向滚动条紧跟着一个特定的元素,比如`wtHider`,这通常是通过CSS样式来控制的。`wtHider`是HandsonTable中的一个元素,用于隐藏工作表中的滚动条。为了使得滚动条能够紧跟着`wtHider`,你需要考虑以下几个方面: 1. **确保CSS定位正确**:通常需要设置`wtHider`的`position`属性为`relative`或者`absolute`,这样它的子元素`div`(包含竖向滚动条的部分)可以通过设置`position: absolute`来相对于它定位。 2. **使用适当的CSS布局**:为了使滚动条紧跟`wtHider`,可能需要使用Flexbox或者CSS Grid布局。例如,你可以设置外层容器的`display`属性为`flex`或`grid`,并相应地调整其子元素的排列。 3. **调整滚动条的样式**:如果HandsonTable提供了滚动条样式的自定义选项,那么你可以通过CSS覆盖默认样式,或者使用JS来动态调整滚动条的样式。 下面给出一个简单的CSS示例,假设`wtHider`是滚动条的父容器,它被设置为`position: relative`,而滚动条的容器设置为`position: absolute`,这样滚动条就可以紧跟在`wtHider`的后面了: ```css .wtHider { position: relative; /* 其他相关样式 */ } .scrollable-content { position: absolute; top: 0; right: 0; bottom: 0; width: 100%; /* 根据需要调整宽度 */ /* 其他相关样式 */ } ``` 确保你的HandsonTable组件及其父容器有正确的布局和定位,这样滚动条才能正确地显示和工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值