react css 方案_使用React,CSS Grid和Unsplash构建无限滚动图片库(代码挑战#16的解决方案)...

react css 方案

Last week on the code challenge we set out to build an image gallery with Infinte Scroll and consuming the Unsplash API. You can complete the challenge here if you haven't.

上周,在代码挑战赛中,我们着手使用Infinte Scroll构建一个图片库并使用Unsplash API。 如果还没有,您可以在这里完成挑战。

In this post, we shall solve this challenge using React.js, a popular Frontend JavaScript library. Also, Chris solved the challenge live on Twitch, you can also see it in the banner media of this post.

在本文中,我们将使用流行的Frontend JavaScript库React.js解决这一挑战。 此外, 克里斯(Chris) 在Twitch上现场解决了挑战,您也可以在本文的横幅媒体中看到它。

In his solution he built out a simple backend node server to handle all the API requests from Unsplash, thereby protecting the API keys. Also, he used tools like Styled components and CSS grid which make building out awesome interfaces really simple.

在他的解决方案中,他构建了一个简单的后端节点服务器来处理来自Unsplash的所有API请求,从而保护了API密钥。 此外,他使用了样式化组件和CSS网格之类的工具,这些工具使构建出色的界面变得非常简单。

For this post, we shall solve the challenge simply using CSS grid as well.

对于这篇文章,我们也将简单地使用CSS网格来解决挑战。

挑战 ( The Challenge )

We are required to build out the image gallery using the base codepen provided, which includes basic HTML to house and style the images repectively. Also the API endpoint to fetch random images was provided. You can find the base code here.

我们需要使用提供的基本codepen构建图像库,其中包括基本HTML,以分别容纳和设置图像的样式。 还提供了用于提取随机图像的API端点。 您可以在此处找到基本代码。

解决方案 ( The Solution )

To solve this challenge, we would use React.js to build out the interface, utilize Axios to make the HTTP requests, and use the react-infinite-scroll library to implement the infinite scroll feature. We shall do these in 5 steps:

为了解决这一挑战,我们将使用React.js来构建接口,利用Axios发出HTTP请求,并使用react-infinite-scroll库来实现无限滚动功能。 我们将分5个步骤进行操作:

  1. Install all required packages

    安装所有必需的软件包
  2. Build the base component to house the images

    构建基础组件以容纳图像
  3. Build a simple image component

    构建一个简单的图像组件
  4. Fetch the random images from Unsplash and render the images

    从Unsplash获取随机图像并渲染图像
  5. Style the gallery

    设置画廊风格

Also, for this challenge, we'll employ React Hooks, which shipped in react 16.8, thus, using functional components throughout the project.

同样,为了应对这一挑战,我们将使用React Hooks,它在react 16.8中提供,因此在整个项目中都使用功能组件。

安装所需的软件包 (Install required packages)

Import all required dependencies from a CDN. Codepen provides a search bar with which you can type in the nameof the module and you can select one from the result and it adds it to your project. Dependencies installed are:

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

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

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

构建基础组件 (Build the base component)

In React, the HTML template for the parent component is written in JSX, we shall proceed to write these HTML elements which make the template, in JSX. Create a functional component and render on the DOM with:

在React中,父组件HTML模板是用JSX编写的,我们将继续在JSX中编写构成模板的这些HTML元素。 创建一个功能组件,并使用以下命令在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 simply created the parent compoenent Collage , returned the HTML elements in JSX and rendered it in the DOM element with id of root. Bulma classes were used to provide basic styling of the page.

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

构建单个图像组件 (Build a single image component)

We move on to create a single component for a single image fetched. This would 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 compoennt we use the <img/> element to display the fetched image.

该组件接收urlkey的属性,即要显示的图像的URL和每个渲染图像的密钥。 在组件中,我们使用<img/>元素显示获取的图像。

从未飞溅中获取随机图像并渲染图像 (Fetch random images from unsplash and render images)

Unsplash provides a free API to fetch random images from which we'll use. 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. In the Collage component, create two state variables, one to hold the incoming images and the other to store a boolean if the images are loaded or not.

Unsplash提供了免费的API,可从中获取随机图像。 图像将存储在状态容器中,并从状态传递到DOM。 由于我们将使用react挂钩,因此我们将分别使用useStateuseEffect处理状态和生命周期方法。 在Collage组件中,创建两个状态变量,一个用于保存传入的图像,另一个用于存储布尔值(无论是否加载图像)。

[...]

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

[...]

Next, we'll create a function which fetches 10 random images using Axios. This is done by making a GET request to the API endpoint whilst 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 we have images stored in state, let's call this fetchImages function once the component in mounted. Previously, we would do this with the componentDidMount lifecycle method. However, React provides the useEffect hook to handle all lifecycle operations in a functional component. In the Collage component, call fetchImages on mount with:

现在,我们已将图像存储在状态中,一旦挂载了组件,就将其称为fetchImages函数。 以前,我们将使用componentDidMount生命周期方法执行此操作。 但是,React提供了useEffect挂钩来处理功能组件中的所有生命周期操作。 在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 for everytime the array is updated or modified.

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

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

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

React-infinite-scroll-component is a simple component which we imported earlier and 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 apporaches view, and display 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是一个简单的组件,我们之前已导入它,它能够显示加载微调器或任何元素作为占位符,一旦加载器处于视图或Apporaches视图中,便调用函数以获取更多数据并显示任何指定的数据。 在返回的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 simply calls the fetchImages function and passes a parameter of 5 which is the number of images to be fetched subsequently. 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组件渲染每个图像。

For this we'll use CSS grid to stlye 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 having 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. To create a masonry, we used the grid-column-end property on the every 5th image to make it take up 2 image space instead of 1.

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

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 solution post 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 masonry. Watch this video on Youtube to see the solution as well. Watch out for the next challenge. Happy coding!

在此解决方案中,我们使用React钩子以及CSS网格构建了一个图片库。 您可以尝试使用网格来创建更好的砌体。 在YouTube上观看此视频,以查看解决方案。 提防下一个挑战。 编码愉快!

翻译自: https://scotch.io/tutorials/build-an-infinite-scroll-image-gallery-with-react-css-grid-and-unsplash-solution-to-code-challenge-16

react css 方案

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值