javascript - 更新浏览器滚动上的进度条状态

标签 javascript reactjs

我正在尝试创建一个进度条,当我滚动时,它会增加/减少其宽度%。我目前正在控制台日志中显示滚动的百分比,但我无法使用滚动的百分比设置状态。

根据我现在得到的信息,我发现 this.percentScrolled() 不是一个函数,因为我是从 componentDidMount 调用它的。我的第二个问题是这样做的性能,每次滚动状态都会更新很多。

这就是我现在得到的,感谢任何帮助。

import React from "react";
import { Line } from "rc-progress";

class ProgressBar extends React.Component {
  constructor() {
    super();

    this.state = {
      percent: 0
    };

    this.percentScrolled = this.percentScrolled.bind(this)
  }

  componentDidMount() {
    window.addEventListener(
      "scroll",
      function() {
        this.percentScrolled();
      },
      false
    );
  }

  getDocHeight = () =>  {
    const d = document;
    return Math.max(
      d.body.scrollHeight,
      d.documentElement.scrollHeight,
      d.body.offsetHeight,
      d.documentElement.offsetHeight,
      d.body.clientHeight,
      d.documentElement.clientHeight
    );
  }

  percentScrolled = () => {
    const winHeight =
      window.innerHeight ||
      (document.documentElement || document.body).clientHeight;
    const docHeight = this.getDocHeight();
    const scrollTop =
      window.pageYOffset ||
      (document.documentElement || document.body.parentNode || document.body)
        .scrollTop;
    const trackLength = docHeight - winHeight;
    const pctScrolled = Math.round((scrollTop / trackLength) * 100);
    console.log("Scrolled: " + pctScrolled + "%");

    this.setState({
      percent: pctScrolled
     });
  }
  render() {
    return (
      <div>
        <Line
          percent={this.state.percent}
          strokeWidth="1"
          strokeColor="green"
          trailColor="white"
        />
      </div>
    );
  }
}

export default ProgressBar;

最佳答案

您调用的 this.percentScrolled 超出了范围。如果您提取匿名函数,它应该在您的组件上下文中正确引用。

尝试:

  componentDidMount() {
    window.addEventListener(
      "scroll",
       this.percentScrolled,
       false
    );
  }

关于javascript - 更新浏览器滚动上的进度条状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52746860/

相关文章:

javascript - axios 在react中忽略baseURL

javascript - 找到数组中的最小值并添加类

javascript - Chartist 总是留有间距?

javascript - CKeditor allowedContent 行为异常

javascript - 使用 Angular 4 的 Ionic 3 中组件和提供者(用于全局变量)之间的两种方式数据绑定(bind)

javascript - 使用 forEach 过滤 JSON 对象

css - React Radium - 如何动态更改属性值

reactjs - 三元条件 - 尝试添加类错误

javascript - 根据单击的父元素选择 h2 元素

javascript - 如何删除包含所有空值的数组列?