ReactJS: React CountUp visible only once in visibility sensor

♀尐吖头ヾ 提交于 2020-06-01 05:11:12

问题


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>

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.


回答1:


You probably don’t want to toggle state unconditionally but rather just set it to true once your visibility sensor calls its onChange callback with isVisible=true

So, something like this (i havent tested it):

function handleVisibility(isVisible) {
!scrollStatus &&
isVisible &&
setScroll(isVisible);
}

<VisibilitySensor onChange={handleVisibility}>



回答2:


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.

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>
    );
  }



来源:https://stackoverflow.com/questions/56928771/reactjs-react-countup-visible-only-once-in-visibility-sensor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!