react 实现滚动加载_如何在React中实现平滑滚动

news/2024/7/8 3:48:03

react 实现滚动加载

介绍 (Introduction)

Smooth scrolling is when instead of clicking on a button and being instantly taken to a different part of the same page, the user is navigated there via a scroll animation. It’s one of those subtle UI features on a site that makes an aesthetic difference.

平滑滚动是指当用户单击滚动动画而不是单击按钮并立即转到同一页面的不同部分时。 它是网站上那些微妙的UI功能之一,在美学上有所作为。

In this article, you are going to use the react-scroll package on npm to implement smooth scrolling.

在本文中,您将在npm上使用react-scroll包来实现平滑滚动。

先决条件 (Prerequisites)

You will need the following to complete this tutorial:

您将需要以下内容才能完成本教程:

  • A valid Git installation. To set this up, review the Getting Started with Git tutorial.

    有效的Git安装。 要进行设置,请查看Git入门教程。

  • Node.js installed locally, which you can do by following the How to Install Node.js and Create a Local Development Environment tutorial.

    Node.js在本地安装,您可以按照“ 如何安装Node.js和创建本地开发环境”教程中的步骤进行操作。

This tutorial was verified with Node v13.14.0, npm v6.14.5, react v16.13.1, and react-scroll v.1.7.16.

本教程已通过Node v13.14.0,npm v6.14.5, react v16.13.1和react-scroll v.1.7.16进行了验证。

快速入门:使用react-scroll (Quickstart: Using react-scroll)

You’ll be building a simple app in this tutorial, but if you want a quick rundown of how react-scroll works, feel free to reference these condensed steps:

您将在本教程中构建一个简单的应用程序,但是如果要快速了解react-scroll工作原理,请随时参考以下简要步骤:

Install react-scroll:

安装react-scroll

npm i -S react-scroll

Import the react-scroll package:

导入react-scroll软件包:

import { Link, animateScroll as scroll } from "react-scroll";

Add the link component. The <Link /> component will point to a certain area of your app:

添加链接组件。 <Link />组件将指向您应用程序的特定区域:

<Link to="section1">

Let’s take a deeper dive and build a little React app with smooth scrolling.

让我们更深入地研究,并通过平滑滚动构建一个小的React应用程序。

第1步—安装并运行React App (Step 1 — Install and Run a React App)

For convenience, this tutorial will use a starter React project (using Create React App 2.0) that has a navigation bar (or navbar) at the top along with five different sections of content.

为方便起见,本教程将使用一个入门级React项目 (使用Create React App 2.0),该项目的顶部具有导航栏(或navbar )以及五个不同的内容部分。

The links in the navbar are just anchor tags at this point, but you will update them shortly to enable smooth scrolling.

导航栏中的链接目前仅是锚标记,但是您将很快对其进行更新以实现平滑滚动。

You can find the project at React With Smooth Scrolling. Please note that this link is for the start branch. The master branch includes all of the finished changes.

您可以在React With Smooth Scrolling中找到项目。 请注意,此链接用于开始分支。 master分支包括所有完成的更改。

To clone the project, you can use the following command:

要克隆项目,可以使用以下命令:

git clone https://github.com/do-community/React-With-Smooth-Scrolling.git

If you look into the src/Components directory, you’ll find a Navbar.js file that contains the <Navbar> with nav-items corresponding to five different <Section>s.

如果查看src/Components目录,则会找到一个Navbar.js文件,其中包含<Navbar>以及与五个不同的<Section>相对应的nav-items

src/Components/Navbar.js
src / Components / Navbar.js
import React, { Component } from "react";
import logo from "../logo.svg";

export default class Navbar extends Component {
  render() {
    return (
      <nav className="nav" id="navbar">
        <div className="nav-content">
          <img
            src={logo}
            className="nav-logo"
            alt="Logo."
            onClick={this.scrollToTop}
          />
          <ul className="nav-items">
            <li className="nav-item">Section 1</li>
            <li className="nav-item">Section 2</li>
            <li className="nav-item">Section 3</li>
            <li className="nav-item">Section 4</li>
            <li className="nav-item">Section 5</li>
          </ul>
        </div>
      </nav>
    );
  }
}

Then, if you open up the App.js file in the src directory, you’ll see where the <Navbar> is included along with the five actual <Section>s"

然后,如果您打开src目录中的App.js文件,您将看到<Navbar>位置以及五个实际的<Section> s”

src/Components/App.js
src / Components / App.js
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import Navbar from "./Components/Navbar";
import Section from "./Components/Section";
import dummyText from "./DummyText";
class App extends Component {
  render() {
    return (
      <div className="App">
        <Navbar />
        <Section
          title="Section 1"
          subtitle={dummyText}
          dark={true}
          id="section1"
        />
        <Section
          title="Section 2"
          subtitle={dummyText}
          dark={false}
          id="section2"
        />
        <Section
          title="Section 3"
          subtitle={dummyText}
          dark={true}
          id="section3"
        />
        <Section
          title="Section 4"
          subtitle={dummyText}
          dark={false}
          id="section4"
        />
        <Section
          title="Section 5"
          subtitle={dummyText}
          dark={true}
          id="section5"
        />
      </div>
    );
  }
}

export default App;

Each <Section> component takes in a title and subtitle.

每个<Section>组件都有一个titlesubtitle

Since this project is using dummy text in the different sections, to reduce repeating code this text was added to a DummyText.js file, imported, and passed into each <Section> component.

由于此项目在不同部分中使用了伪文本,因此为了减少重复代码,将此文本添加到DummyText.js文件中,然后导入并传递到每个<Section>组件中。

To run the app, you can use the following commands.

要运行该应用程序,可以使用以下命令。

  • cd React-With-Smooth-Scrolling

    cd React-With-Smooth-Scrolling

  • npm install

    npm安装
  • npm start

    npm开始

This will start the app in development mode and automatically refresh the app when you save on of your files. You can view it in the browser at localhost:3000.

这将在开发模式下启动应用程序,并在保存文件时自动刷新应用程序。 您可以在浏览器中的localhost:3000查看它。

第2步—安装和配置React-Scroll (Step 2 — Installing and Configuring React-Scroll)

Now it’s time to install the react-scroll package and add that functionality. You can find information for the package on npm.

现在是时候安装react-scroll软件包并添加该功能了。 您可以在npm上找到有关该软件包的信息。

To install the package, run the following command:

要安装该软件包,请运行以下命令:

  • npm install react-scroll

    npm install react-scroll

Next, open the Navbar.js file back up and add an import for two named imports, Link and animateScroll.

接下来,打开备份的Navbar.js文件,并为两个命名的导入( LinkanimateScroll添加一个import

src/Components/Navbar.js
src / Components / Navbar.js
import { Link, animateScroll as scroll } from "react-scroll";

Notice that I’ve aliased animatedScroll to scroll for ease of use.

请注意,我为animatedScroll scroll了别名,以便于scroll使用。

With all of your imports defined, you can now update your nav-items to use the <Link> component. This component takes several properties. You can read about all of them on the documentation page.

定义了所有导入后,您现在可以更新nav-items以使用<Link>组件。 该组件具有多个属性。 您可以在文档页面上阅读所有这些内容。

For now, pay special attention to activeClass, to, spy, smooth, offset, and duration.

现在,要特别注意activeClasstospysmoothoffsetduration

  • activeClass - The class applied when element is reached.

    activeClass到达元素时应用的类。

  • to - The target to scroll to.

    to -滚动到的目标。

  • spy - To make Link selected when scroll is at its target’s position.

    spy -在scroll位于其目标位置时选择“ Link

  • smooth - To animate the scrolling.

    smooth -动画化滚动。

  • offset - To scroll additional px (like padding).

    offset -滚动其他像素(如填充)。

  • duration - The time of the scroll animation. This can be a number or a function.

    duration滚动动画的时间。 这可以是数字或函数。

The to property is the most important part as it tells the component which element to scroll to. In this case, this will be each of your <Section>s.

to属性是最重要的部分,因为它告诉组件滚动到哪个元素。 在这种情况下,这将是您的每个<Section>

With the offset property, you can define an additional amount of scrolling to perform to get to each <Section>.

使用offset属性,您可以定义执行到每个<Section>的附加滚动量。

Here’s an example of the properties that you will use for each <Link> component. The only difference between them will be the to property as they each point to a different <Section>:

这是您将用于每个<Link>组件的属性的示例。 它们之间的唯一区别是to属性,因为它们每个都指向不同的<Section>

<Link
    activeClass="active"
    to="section1"
    spy={true}
    smooth={true}
    offset={-70}
    duration={500}
>

You’ll need to update each of the nav-items accordingly. With these added, you should be able to go back to your browser (your app should have automatically restarted already) and see smooth scrolling in action.

您需要相应地更新每个nav-items 。 添加这些功能后,您应该可以返回浏览器(您的应用程序应该已经自动重启),并可以流畅地滚动查看。

The activeClass property allows you to define a class to apply to the <Link> component when its to element is active. A <Link> is considered active if its to element is in view near the top of the page. This can be triggered by clicking on the <Link> itself or by scrolling down to the <Section> manually.

所述activeClass属性,可以定义一个类应用到<Link>组件时其to元件是活动的。 如果<Link>在页面顶部附近,则认为它是to元素。 可以通过单击<Link>本身或手动向下滚动到<Section>来触发。

To prove this, I opened up the Chrome DevTools and inspected the fifth <Link> as shown below. When I clicked on that <Link> or manually scrolled to the bottom of the page, I noticed that the active class is, in fact, applied.

为了证明这一点,我打开了Chrome DevTools并检查了第五个<Link> ,如下所示。 当我单击该<Link>或手动滚动到页面底部时,我注意到实际上已应用了活动类。

To take advantage of this, you can create an active class and add an underline to the link. You can add this bit of CSS in the App.css file in the src directory:

要利用此优势,您可以创建一个活动类,并在链接中添加下划线。 您可以在src目录的App.css文件中添加以下CSS:

src/App.css
src / App.css
.nav-item > .active {
    border-bottom: 1px solid #333;
}

Now, if you go back to your browser and scroll around a bit, you should see the appropriate <Link> is underlined.

现在,如果返回浏览器并滚动一下,您应该看到相应的<Link>带下划线。

步骤4 —添加其他功能 (Step 4 — Adding Additional Functions)

For one last bit of content, this package also provides some functions that can be called directly like scrollToTop, scrollToBottom, etc. As well as various events that you can handle.

对于内容的最后一点,此包还提供了一些可以直接调用的功能,例如scrollToTopscrollToBottom等。以及可以处理的各种事件。

In reference to these functions, typically, the application logo in a navbar will bring the user to the home page or the top of the current page.

参考这些功能,通常,导航栏中的应用程序徽标会将用户带到主页或当前页面的顶部。

As a simple example of how to call one of these provided functions, I added a click handler to the nav-logo to scroll the user back to the top of the page, like so:

作为如何调用这些提供的功能之一的简单示例,我在nav-logo添加了一个单击处理程序,以将用户滚动回到页面顶部,如下所示:

src/Components/Navbar.js
src / Components / Navbar.js
scrollToTop = () => {
    scroll.scrollToTop(); 
};

Back in the browser, you should be able to scroll down on the page, click the logo in the navbar, and be taken back to the top of the page.

返回浏览器,您应该能够向下滚动页面,单击导航栏中的徽标,然后回到页面顶部。

结论 (Conclusion)

Smooth scrolling is one of those features that can add a lot aesthetic value to your application. The react-scroll package allow you to leverage this feature without significant overhead.

平滑滚动是可以为您的应用程序增加很多美学价值的那些功能之一。 react-scroll软件包使您可以利用此功能而不会产生大量开销。

In this tutorial, you added smooth scrolling to an app and experimented with different settings. If you’re curious, spend some time exploring the other functions and events that this package has to offer.

在本教程中,您向应用程序添加了平滑滚动,并尝试了不同的设置。 如果您好奇,请花一些时间探索此程序包必须提供的其他功能和事件。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-implement-smooth-scrolling-in-react

react 实现滚动加载


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

相关文章

jsp、freemarker、velocity、thymeleaf模板引擎优缺点

1、概述 在java领域&#xff0c;表现层技术主要有三种&#xff0c; &#xff08;1&#xff09;jsp; &#xff08;2&#xff09;freemarker; &#xff08;3&#xff09;velocity; &#xff08;4&#xff09;thymeleaf; 2、jsp 优点&#xff1a; 1、功能强大&#xff0c;可…

X Window研究笔记(22)

X Window研究笔记(22)转载时请注明出处和作者联系方式作者联系方式&#xff1a;李先静 22.X Window 简单示例对大多数linux程序员来说&#xff0c;很少有机会直接用Xlib去开发应用程序&#xff0c;那样开发效率太低&#xff0c;一般都是使用基于像GTK&#xff0b;和QT这样的too…

discord china_如何在Ubuntu 18.04上使用Discord Webhooks获取有关您的网站状态的通知

discord chinaThe author selected the Apache Software Foundation to receive a donation as part of the Write for DOnations program. 作者选择了Apache Software Foundation作为Write for DOnations计划的一部分来接受捐赠。 介绍 (Introduction) When you have critica…

Java中transient关键字

Java中transient关键字1.只要这个类实现了Serilizable接口&#xff0c;这个类的所有属性和方法都会自动序列化。 2.如果在实现了Serilizable接口的类中&#xff0c;对该类的某属性添加transient关键字&#xff0c;那么在序列化对象的时候&#xff0c;这个属性就不会被序列化。…

蓝牙协议读书笔记

蓝牙协议读书笔记转载时请注明出处和作者联系方式作者联系方式&#xff1a;李先静 昨天翻了一下Multimedia.Wireless.Networks.Technologies.Standards.and.QoS&#xff0c;看了其中的bluetooth一章&#xff0c;虽然还有很多细节没有搞明白&#xff0c;不过基本框架还是清楚了&…

如何在Ubuntu 20.04上使用Postgres,Nginx和Gunicorn设置Django

介绍 (Introduction) Django is a powerful web framework that can help you get your Python application or website off the ground. Django includes a simplified development server for testing your code locally, but for anything even slightly production related…

linux蓝牙驱动代码阅读笔记

linux蓝牙驱动代码阅读笔记转载时请注明出处和作者联系方式作者联系方式&#xff1a;李先静 昨天看了一下介绍蓝牙协议文档&#xff0c;今天索性对照看了看kernel里的代码(bluez)&#xff0c;这里记点笔记&#xff0c;还是继承了老毛病&#xff0c;只关注整体流程而忽略细节&am…

acme.sh 更换dns_如何在Ubuntu 18.04上使用acme-dns-certbot使用DNS验证来获取让我们加密证书

acme.sh 更换dnsThe author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program. 作者选择了COVID-19救济基金来接受捐赠&#xff0c;这是Write for DOnations计划的一部分。 介绍 (Introduction) The majority of Let’s …