一种知道React组件何时进入浏览器视口的简便方法

In this article, you’ll learn how to use React Visibility Sensor to detect when your React components have entered the viewport.

在本文中,您将学习如何使用React Visibility Sensor检测React组件何时进入视口。

How do you programmatically determine when a React component enters the viewport? Well, it ain’t easy! It requires a good deal of scrolling event listeners, calculating the sizes of your elements… Ahhhn no fun!

您如何以编程方式确定React组件何时进入视口 ? 好吧,这并不容易! 它需要大量的滚动事件侦听器,计算元素的大小……啊,没什么好玩的!

Using React Visibility Sensor provides you with a React component that accomplishes this using a really simple API.

使用React Visibility Sensor为您提供了一个React组件,可使用一个非常简单的API来完成此任务。

在深处滚动 (Scrollin’ In the Deep)

Let’s jump right into a demo!

让我们直接进入演示!

Try scrolling the page. The images become “aware” when they’ve entered the viewport…

尝试滚动页面。 进入视口后,图像将变得“可识别”。

This functionality is pretty easy to build with React Visibility Sensor. We’ll look at two React components to see how this demo was made.

使用React Visibility Sensor可以轻松构建此功能。 我们将查看两个React组件,以了解此演示的制作方式。

First, the <img> component that relies on visibility detection…

首先,依赖可见性检测的<img>组件…

VizImageAware.js
VizImageAware.js
import React, { Component } from 'react';
import VizSensor from 'react-visibility-sensor';

class VizAwareImg extends Component {
  state = {
    imgViz: false
  }
  render() {
    return (
      <VizSensor
        onChange={(isVisible) => {
          this.setState({imgViz: isVisible})
        }}
      >
        <img
          src={this.props.src}
          style={{
            width: 300,
            height: 300,
            opacity: this.state.imgViz ? 1 : 0.25,
            transition: 'opacity 500ms linear'
          }}
        />
      </VizSensor>
    );
  }
}

And below is the App component. It isn’t crucial to deeply analyze the code below. I’m just providing it to give you the big picture of this demo:

下面是App组件。 深入分析下面的代码并不是至关重要的。 我只是为了向您展示此演示的概况:

App.js
App.js
import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div style={{background: 'violet', color: 'purple'}}>

        <div style={{height: '100vh'}}>
          <div>Jellyfish</div>
          <div>⏬</div>
        </div>

        {[
          'https://unsplash.com/jellyfish-1.jpeg',
          'https://unsplash.com/jellyfish-2.jpeg',
          'https://unsplash.com/jellyfish-3.jpeg',
          'https://unsplash.com/jellyfish-4.jpeg',
          'https://unsplash.com/jellyfish-5.jpeg',
          'https://unsplash.com/jellyfish-6.jpeg'
        ].map((imgpath) => <VizAwareImg src={imgpath}/>)}

    </div>
    );
  }
}

There’s actually quite a bit of customization props you can provide to React Visibility Sensor. One of the customizations I usually make is to allow for partialVisibility of elements.

实际上,您可以为React Visibility Sensor提供很多自定义道具。 我通常进行的自定义之一是允许元素的partialVisibility

自定义React可见性传感器 (Customizing React Visibility Sensor)

If you scroll back to the demo, the images only appear when they’ve fully entered the viewport. However, it may be desirable to know when just a part of the element has entered the viewport.

如果您滚动回到演示,则图像仅在它们完全进入视口时显示 。 但是,可能希望知道何时只有一部分元素进入视口。

class VizAwareImg extends Component {
  state = {
    imgViz: false
  }
  render() {
    return (
      <VizSensor
        partialVisibility {/* 👈 BOOM! Just add that... */}
        onChange={(isVisible) => {
          this.setState({imgViz: isVisible})
        }}
      >
        <img
          src={this.props.src}
          style={{
            opacity: this.state.imgViz ? 1 : 0.25,
            width: 300,
            height: 300,
            transition: 'opacity 500ms linear'
          }}
        />
      </VizSensor>
    );
  }
}

Now, if you scroll the page the image’s opacity changes when it barely creeps into the viewport (you may need a desktop-sized screen to see this):

现在,如果滚动页面,则图像的不透明度几乎会爬入视口(您可能需要一个桌面大小的屏幕才能看到它)时发生变化:

In addition to partialVisibility there are many customization props, like:

除了partialVisibility,还有许多自定义道具,例如:

  • Throttling the scroll listener

    限制滚动侦听器
  • Specifying the minimum number of pixels to appear in the viewport (default: when partialVisibility is true elements are considered visible when only 1px appears)

    指定在视口中显示的最小像素数(默认值: partialVisibilitytrue时,仅显示1px时,元素被视为可见)

  • Listen when the browser window is resized

    调整浏览器窗口大小时收听
  • Or just deactivating the scroll listener all together if you don’t need to listen for the event any longer

    或者,如果您不再需要侦听该事件,则只需一起停用滚动侦听器

Images are from the amazing community of Unsplash.com photographers

图片来自Unsplash.com摄影师的惊人社区

结语 (Wrapping Up)

Being self-aware is one of the greatest powers that you can aspire to have… I’m talking about React.js!

自我意识是您可以渴望拥有的最大力量之一……我在谈论React.js!

When your React components know they’re visible, your app can do more sophisticated things. For example:

当您的React组件知道它们可见时,您的应用程序可以执行更复杂的事情。 例如:

  • Lazy-loading images when they’re visible

    可见时延迟加载图像
  • Show a “Thanks for Visiting!” message when users have scrolled to the footer of your website

    显示“感谢您的光临!” 用户滚动到您网站的页脚时出现的消息
  • Logging custom events to Google Analytics

    将自定义事件记录到Google Analytics(分析)
  • Expand a comment widget when users scroll to the end of a blog post

    当用户滚动到博客文章的末尾时,展开评论小部件
  • … And more!

    … 和更多!

View the documentation on Github

查看有关Github的文档

翻译自: https://www.digitalocean.com/community/tutorials/react-components-viewport-react-visibility-sensor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值