还在学习反应,有几个例子,我正在努力了解各州&道具。希望有人能告诉我如何转换下面的内容。
const display = document.querySelector('#time');
const countdown = new CountDownTimer(120);
const timeObj = CountDownTimer.parse(120);
format(timeObj.minutes, timeObj.seconds);
countdown.onTick(format);
document.querySelector('button').addEventListener('click', () => {
countdown.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? `0${minutes}` : minutes;
seconds = seconds < 10 ? `0${seconds}` : seconds;
display.textContent = `${minutes}:${seconds}`;
}
<script src="https://cdn.rawgit.com/robbmj/simple-js-countdown-timer/master/countdowntimer.js"></script>
<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>
<body>
<button>Start Count Down</button>
<div>Registration closes in <span id="time"></span> minutes!</div>
</body>
答案 0 :(得分:2)
你需要做的就是做一个作为你的计时器的反应类。
这是一个粗略的概述,您可能需要稍微使用数据..但应该让您入门。注意,它接受毫秒并转换为秒和分钟
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
ms: props.ms
}
}
componentWillMount() {
this.interval = setInterval( () => {
if ((this.state.ms) <= 0) {
clearInterval(this.interval);
this.forceUpdate();
return;
}
this.setState({ms: this.state.ms - 1000});
}, 1000)
}
componentWillUnmount() {
clearInterval(this.interval);
}
format() {
const { ms } = this.state;
let seconds = Math.floor(ms / 1000);
let minutes = Math.floor(seconds / 60);
minutes = minutes < 1 ? '00' : minutes < 10 ? `0${minutes}` : minutes;
seconds = seconds < 1 ? '00' : seconds < 10 ? `0${seconds}` : seconds;
return `${minutes}:${seconds}`;
}
render() {
return (
<div>{this.format(this.state.ms)}</div>
)
}
}
你使用它的方式就像......
<Timer ms={15000} />