ReactJS:React CountUp 在可见性传感器中仅可见一次 [英] ReactJS: React CountUp visible only once in visibility sensor

查看:69
本文介绍了ReactJS:React CountUp 在可见性传感器中仅可见一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个具有可见性传感器的页面,以便每当我滚动到该部分时,动画就会开始.但是,我只需要它可见一次.

I am working on a page that has a visibility sensor so that whenever I scroll to that section, the animation starts. However, I only need it to be visible only once.

const [scrollStatus, setScroll] = useState(false);
    const contextData = {
        stateSetters: {
            scrollStatus
        }

    }

<ScrollContext.Provider value={contextData}>
    <VisibilitySensor onChange={() => {
       setScroll(!scrollStatus);
    }}>
    <CountUp start={0} end={scrollStatus ? 0 : 40} duration={1.75} suffix="+"/>
    </VisibilitySensor>
</ScrollContext.Provider>

我目前正在使用钩子和功能组件.我一直在寻找能够在查看后将可见性设置为 true 的方法.

I am currently using hooks and functional components. I have been looking for ways to be able to set the visibility to true once it has been viewed.

输出应该已经可见,而不是在每次滚动时都可见.

The output should become already visible and not visible only every scroll.

推荐答案

正如 dee zg 提到的,你可以通过使用事件属性 isVisible 和属性 active,如以下示例所示.

As mentioned by dee zg, you can set the status of the VisibilitySensor by using the event attribute isVisible and the property active, as roughly shown in the following example.

一个小的运行代码示例可以在 codesandbox 上找到.

A small running code example can be found on codesandbox.

import React from "react";
import VisibilitySensor from "react-visibility-sensor";

class myTest extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            VizSensorActive: true
        };

        this.do_something = this.do_something.bind(this);
    }

    do_something(isVisible) {
        if (isVisible) {
            this.setState({ VizSensorActive: false });
        }
    }

    render() {
        return (
            <VisibilitySensor
                active={this.VizSensorActive}
                onChange={this.do_something}
            >
                <div>Test</div>
            </VisibilitySensor>
        );
    }
}

export default myTest;

这篇关于ReactJS:React CountUp 在可见性传感器中仅可见一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆