react 滚动条组件
Let’s re-implement the progress bar on page scroll effect that you may have seen on many popular blogs including this one.
让我们重新实现页面滚动效果上的进度条,您可能已经在包括该博客在内的许多受欢迎的博客上看到了。
我们将如何做 (How we’ll do it)
To implement this, we would be making use of React, styled-components and the Document
onScroll event. So, without further ado, let’s begin.
为了实现这一点,我们将使用React , 样式组件和Document
onScroll事件。 因此,事不宜迟,让我们开始吧。
安装 (Installation)
As stated, we’ll be using React
and styled-components
to implement the progress scroll effect. In order to save time, we’ll make use of Create React App to bootstrap a quick React application for us.
如前所述,我们将使用React
和styled-components
来实现进度滚动效果。 为了节省时间,我们将使用Create React App为我们引导一个快速的React应用程序。
So open your terminal and run the following commands:
因此,请打开您的终端并运行以下命令:
$ create-react-app app-name
$ cd app-name
Don’t have `create-react-app` installed? Then you can use this command $ npx create-react-app app-name
没有安装“ create-react-app”吗? 然后,您可以使用此命令$ npx create-react-app app-name
Alright so next up we need to also install styled-components
to our newly created project. So while in the project directory, run
好了,接下来我们还需要将styled-components
安装到我们新创建的项目中。 因此,在项目目录中运行
$ npm install styled-components -S
Now if you run npm start
in our terminal, you should see something like this:
现在,如果您在我们的终端中运行npm start
,您应该会看到类似以下内容:
设计布局 (Designing the Layout)
So, now that our application is setup, let’s start writing some actual code. We’ll begin by building our page layout and writing some CSS to style the layout.
因此,既然我们的应用程序已经设置好,让我们开始编写一些实际的代码。 首先,我们将构建页面布局并编写一些CSS来设置布局样式。
Navigate to your src/App.js
file and then delete everything in the file and add the following lines of code:
导航到src/App.js
文件,然后删除文件中的所有内容并添加以下代码行:
import React, { Component } from 'react';
import './App.css';
export default class App extends Component {
render() {
return (
<div className="App">
<header></header>
<main>
<h1>Lorem Ipsum</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>...more paragraphs of text, enough so that the page gets a scrollbar</p>
</main>
</div>
);
}
}
Basically what we just did is convert the stateless functional component th