0
我有一個非常混亂的任務,我需要你的幫助。 我需要爲每個任務創建帶定時器的todos。所以用戶可以創建他自己的任務 - >啓動計時器 - >停止計時器 - >關閉任務。每個任務都有按鈕啓動和停止。React的殘疾人按鈕
問題是隻有一個定時器可以同時工作。因此,即使一個定時器工作,也應禁用另一個按鈕「開始」。 我想這個決定靠近handleStartClick(改變數值按鈕?)。
這是代碼的主要部分:
export default class TodoItem extends Component {
constructor(props) {
super(props);
this.state = { secondsStart: this.props.minSeconds }
this.handleStartClick = this.handleStartClick.bind(this)
}
static propTypes = {
todo: PropTypes.object.isRequired,
deleteTodo: PropTypes.func.isRequired,
completeTodo: PropTypes.func.isRequired,
}
static defaultProps = {
minSeconds: 0
}
getSeconds =() => {
return ('0' + this.state.secondsStart % 60).slice(-2)
}
getMinutes =() => {
return Math.floor('0' + this.state.secondsStart/60)
}
getHoures =() => {
return Math.floor(this.state.secondsStart/60)
}
handleSave = (id, text) => {
if (text.length === 0) {
this.props.deleteTodo(id)
}
}
handleStartClick =() => {
this.incrementer = setInterval(() => {
this.setState({secondsStart:(this.state.secondsStart + 1)
});
}, 1000)
}
handleStopClick =() => {
clearInterval(this.incrementer)
}
render() {
const { todo, completeTodo, deleteTodo} = this.props
let element
if (this.state.todo) {
element = (
<TodoTextInput text={todo.text}
onSave={(text) => this.handleSave(todo.id, text)} />
)
} else {
element = (
<div className="view">
<input className="toggle"
type="checkbox"
checked={todo.completed}
onChange={() => completeTodo(todo.id)} />
<label>
{todo.text}
</label>
<div className="buttons">
<h6>{this.getHoures()}:{this.getMinutes()}:{this.getSeconds()}</h6>
{(this.state.secondsStart === 0)
? <button className="timer-start" onClick={this.handleStartClick}>Start</button>
: <button className="timer-stop" onClick={this.handleStopClick}>Stop</button>
}
</div>
<button className="destroy"
onClick={() => deleteTodo(todo.id)} />
</div>
)
}
對不起,也許實在是太大了,但我真的不知道我可以隱藏,或許真的是有用的。 我將非常感謝您的幫助。
正如我右理解,這些狀態我可以控制這樣的: handleStartClick =()=> { this.incrementer =的setInterval(()=> { this.setState({secondsStart:(this.state。 secondsStart + 1) }); },1000) this.setState({timerRunning:true }); } –
是的。檢查反應setState方法的確切細節。 –
謝謝,這對我真的很有幫助。 –