gpt4 book ai didi

javascript - React 中的倒计时器

转载 作者:行者123 更新时间:2023-12-03 13:05:20 28 4
gpt4 key购买 nike

我在 JavaScript 中见过很多倒计时器,并希望在 React 中使用一个。

我借用了网上找到的这个函数:

secondsToTime(secs){
let hours = Math.floor(secs / (60 * 60));

let divisor_for_minutes = secs % (60 * 60);
let minutes = Math.floor(divisor_for_minutes / 60);

let divisor_for_seconds = divisor_for_minutes % 60;
let seconds = Math.ceil(divisor_for_seconds);

let obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
};

然后我自己编写了这段代码

  initiateTimer = () => {
let timeLeftVar = this.secondsToTime(60);
this.setState({ timeLeft: timeLeftVar })
};

startTimer = () => {
let interval = setInterval(this.timer, 1000);
this.setState({ interval: interval });
};

timer = () => {
if (this.state.timeLeft >0){
this.setState({ timeLeft: this.state.timeLeft -1 });
}
else {
clearInterval(this.state.interval);
//this.postToSlack();
}
};

当前 onclick 会将屏幕上的时间设置为:剩余时间:1 m : 0 s但它不会将其减少到 Time Remaining: 0 m : 59 s 然后 Time Remaining: 0 m : 58 s 等等

我想我需要使用不同的参数再次调用该函数。我该如何去做呢?

编辑:我忘了说,我想要这个功能,以便我可以使用秒到分钟和秒

最佳答案

您必须在剩余的秒数内每秒setState(每次调用间隔时)。这是一个例子:

class Example extends React.Component {
constructor() {
super();
this.state = { time: {}, seconds: 5 };
this.timer = 0;
this.startTimer = this.startTimer.bind(this);
this.countDown = this.countDown.bind(this);
}

secondsToTime(secs){
let hours = Math.floor(secs / (60 * 60));

let divisor_for_minutes = secs % (60 * 60);
let minutes = Math.floor(divisor_for_minutes / 60);

let divisor_for_seconds = divisor_for_minutes % 60;
let seconds = Math.ceil(divisor_for_seconds);

let obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}

componentDidMount() {
let timeLeftVar = this.secondsToTime(this.state.seconds);
this.setState({ time: timeLeftVar });
}

startTimer() {
if (this.timer == 0 && this.state.seconds > 0) {
this.timer = setInterval(this.countDown, 1000);
}
}

countDown() {
// Remove one second, set state so a re-render happens.
let seconds = this.state.seconds - 1;
this.setState({
time: this.secondsToTime(seconds),
seconds: seconds,
});

// Check if we're at zero.
if (seconds == 0) {
clearInterval(this.timer);
}
}

render() {
return(
<div>
<button onClick={this.startTimer}>Start</button>
m: {this.state.time.m} s: {this.state.time.s}
</div>
);
}
}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

关于javascript - React 中的倒计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40885923/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com