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.
此组件接收url
和key
的url
,这是要显示的图像的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,因此我们将分别使用useState
和useEffect
处理状态和生命周期方法。
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中,以及在带有一类header
的div
之后,使用以下命令在无限滚动组件中渲染图像:
<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
组件渲染每个图像。
步骤5 —样式库 (Step 5 — Styling the Gallery)
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无限滚动