在浏览器滚动条上更新进度条状态

时间:2018-10-10 18:44:54

标签: 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;

1 个答案:

答案 0 :(得分:1)

您正在呼叫this.percentScrolled,超出范围。如果退出匿名函数,它应该在Component上下文中正确引用。

尝试:

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