【问题标题】:How to render the actual value of the scroll percentage?如何渲染滚动百分比的实际值?
【发布时间】:2021-08-25 14:10:50
【问题描述】:

我有这段代码

import React from 'react'

const App = () => {  

function getScrollPercent() {
  var h = document.documentElement, 
    b = document.body,
    st = 'scrollTop',
    sh = 'scrollHeight';

  var scrollPercent = Math.round((h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100);
  //get the percentage of scroll

  return (isNaN(scrollPercent) ? '' : scrollPercent)
}

return (
  <p>{`${getScrollPercent()}%`}</p>
)

问题是当我滚动时,scrollPercent 不会实时刷新,而只会在滚动停止时刷新,所以 scrollPercent 可以从 0% 传递到 100% 并且不显示 0 到 100 之间的所有数字,所以问题是即使滚动,我如何修改我的代码以显示 scrollPercent 的实际值

【问题讨论】:

    标签: javascript reactjs animation scroll


    【解决方案1】:

    您需要使用useEffect 来添加一个监听滚动事件的事件监听器。然后,您可以注册一个函数,该函数将在用户向上或向下滚动页面时重新计算滚动位置。

    import React, { useEffect, useState } from "react";
    
    function getScrollPercent() {
      var h = document.documentElement,
        b = document.body,
        st = "scrollTop",
        sh = "scrollHeight";
    
      var scrollPercent = Math.round(
        ((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100
      );
      //get the percentage of scroll
    
      return isNaN(scrollPercent) ? "" : scrollPercent;
    }
    
    const App = () => {
      // this represents the current calculated scroll percentage
      // maybe initialize this to something other than empty string
      const [scrollPercentage, setScrollPercentage] = useState("");
    
      useEffect(() => {
        function handleScroll() {
          const newScrollPercentage = getScrollPercent();
    
          // calculate and set the new scroll percentage
          setScrollPercentage(newScrollPercentage);
        }
    
        window.addEventListener("scroll", handleScroll, true);
    
        // clean up event listener when component unmounts
        return () => {
          window.removeEventListener('scroll', handleScroll, true);
        }
      }, []);
    
      // this contains extra styling to demo, so that you can see the 
      // scroll value change when scrolling, probably remove these style props
      return (
        <div style={{ height: "3000px" }}>
          <p style={{ position: "fixed" }}>{`${scrollPercentage}%`}</p>
        </div>
      );
    };
    
    export default App;
    

    Codesandbox 示例链接:Codesandbox

    【讨论】:

      【解决方案2】:

      你需要使用 window.addEventListener 来达到你想要的。

      import React from "react";
      
      const App = () => {
        const [scroll, setScroll] = React.useState("");
      
        function getScrollPercent() {
          var h = document.documentElement,
            b = document.body,
            st = "scrollTop",
            sh = "scrollHeight";
      
          var scrollPercent = Math.round(
            ((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100
          );
      
          setScroll(isNaN(scrollPercent) ? "" : scrollPercent);
        }
      
        React.useEffect(() => {
          window.addEventListener("scroll", getScrollPercent);
      
          return () => {
            window.removeEventListener("scroll", getScrollPercent);
          };
        }, []);
      
        return (
          <div style={{ height: "1000px" }}>
            <p style={{ position: "fixed" }}>{`${scroll}%`}</p>
          </div>
        );
      };
      
      export default App;
      

      Codesanbox 链接:https://codesandbox.io/s/unruffled-field-3l3z8?file=/src/App.js:0-664

      【讨论】:

      • 这将导致额外的开销,因为每次渲染都会重新生成getScrollPercent。此外,缺少导入 useStateuseEffect
      • 不需要导入 useState 和 useEffect,因为它是用 React 调用的。关于开销,我不确定这是真的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多