在React中创建一个平滑的进度条

时间:2018-12-12 02:37:27

标签: reactjs progress-bar setinterval

我创建了一个非常简单的音频播放器,并且使用setInterval来创建进度条的效果。该组件的代码如下:

class AudioPlayer extends Component {
    constructor(props) {
        super(props)
        this.audio = new Audio(file);
    }
    state = {
        playButton: 'play',
        progress: 0,
    }
    componentDidMount = () => {
        this.currentTimeInterval = null;
        this.slider = 0;
        this.audio.onplay = () => {
            this.currentTimeInterval = setInterval( () => {
                this.slider = (this.audio.currentTime * 100) / this.audio.duration;
                this.setState({progress: this.slider})
            }, 100);
        };
    }
    playAudio = () => {
        if (this.state.playButton === 'play') {
            this.audio.play();
            this.setState({playButton: 'pause'});
        } else {
            clearInterval(this.currentTimeInterval);
            this.audio.pause();
            this.setState({playButton: 'play'});
        }
    }
    render() {
        return(
            <div>
                <button onClick={this.playAudio}><FontAwesomeIcon icon="step-backward" /></button>
                <button onClick={this.playAudio}><FontAwesomeIcon icon={this.state.playButton} /></button>
                <button onClick={this.stopAudio}><FontAwesomeIcon icon="stop" /></button>
                <button onClick={this.playAudio}><FontAwesomeIcon icon="step-forward" /></button>
                <div className="progress-bar" style={{width: this.state.progress + '%'}}></div>
            </div>
        )
    }
}

当间隔设置为100时,它看起来还不错,但是如果将其更改为500,则条形图将无法平滑移动。我尝试应用以下CSS代码:

.progress-bar {
  background-color: blue;
  -webkit-transition: width 0.3s ease;
  -o-transition: width 0.3 ease;
  transition: width 0.3 ease;
  height: 20px;
}

但是,当间隔设置为500时,除非我将时间设置为至少5s,否则css过渡将无济于事,这不好,因为它会产生延迟。

所以我的问题是关于性能的-使用100甚至更少的时间间隔是一种好习惯吗?它不会影响每100毫秒重新渲染组件的性能吗?我只是想知道这是否是一个好习惯?

预先感谢

1 个答案:

答案 0 :(得分:0)

尝试这个。您要动画的属性应该存在于同一个类中。我希望我不会被否决:)

.progress-bar {
  width: 0; // try width: 0% if prior one do not work
  background-color: blue;
  -webkit-transition: width 0.3s ease;
  -o-transition: width 0.3 ease;
  transition: width 0.3 ease;
  height: 20px;
}

https://codesandbox.io/s/00qq6yj36w