我在倒数npm库中有以下代码
import React, { Component } from 'react'
import { Panel, Button } from 'rsuite';
import Countdown from 'react-countdown-now';
export default class GamePlay extends Component {
constructor(){
super();
this.state={
select: false
}
this.onSelect = this.onSelect.bind(this);
}
onSelect(e){
this.setState({ select: e.target.name });
}
render() {
return (
<div>
<div className="col-6 offset-3">
<Panel className="text-center bg-white" header={<h3>Question</h3>} bordered>
<div className="d-flex align-items-center">
Time left:
<Countdown date={Date.now() + 30000} />
</div>
</Panel>
</div>
<div className="mt-5">
<div className="d-flex align-items-center">
<div className="col-6">
<Button name="A" appearance={`${this.state.select === 'A' ? 'primary': 'default'}`} block onClick={this.onSelect} bordered>A</Button>
<Button name="C" appearance={`${this.state.select === 'C' ? 'primary' : 'default'}`} block onClick={this.onSelect} bordered>C</Button>
</div>
<div className="col-6">
<Button name="B" appearance={`${this.state.select === 'B' ? 'primary' : 'default'}`} block onClick={this.onSelect} bordered>B</Button>
<Button name="D" appearance={`${this.state.select === 'D' ? 'primary' : 'default'}`} block onClick={this.onSelect} bordered>D</Button>
</div>
</div>
</div>
</div>
)
}
}
当我单击按钮选择答案时,它将导致GamePlay组件重新呈现,因此倒计时重新开始。
当我单击答案时,如何阻止它重新启动?我真的很感谢您的帮助。
答案 0 :(得分:2)
您可以在render函数之外定义date
属性值,这样在重新渲染父级时它不会改变。
这里是一个例子:
constructor(){
....
this.date = Date.now() + 30000;
}
render(){
....
<Countdown date={this.date} />
....
}