【发布时间】:2022-11-10 23:43:18
【问题描述】:
因此,当我单击标题时,我试图通过提示更新小时、分钟和秒值,但我无法这样做。有人可以帮忙吗?
我曾尝试使用 Date 类中的设置器,但没有运气。我相信它与 componentWillMount() 有关,但我不确定如何解决它。
import React, { Component } from 'react'
class Clock extends Component {
constructor()
{
super()
this.state = {time:new Date()}
}
componentWillMount(){
setInterval(() => this.setState({time:new Date()}),1000)
//setInterval(() => this.state.time.setSeconds(1),1000);
}
setHour(){
// alert("This is the hour");
let hour = prompt("Enter the hour you would like to change to" , 12);
//! Not working
this.state.time.setHours(hour);
}
setMinutes(){
//alert("This is the minutes");
let minutes = prompt("Enter the minutes you would like to change to" , 30);
//! Not working
this.state.time.setHours(minutes);
}
setSeconds(){
//alert("This is the seconds");
let seconds = prompt("Enter the seconds you would like to change to" , 35);
//! Not working
this.state.time.setHours(seconds);
}
render() {
return (
<div style={{border: '5px solid black', textAlign: 'center', width: '30%',}}>
<h4 style={{margin: '10px'}} >London Clock </h4>
<h4 onClick={this.setHour} style={{display: 'inline'}}>{this.state.time.toLocaleTimeString().slice(0,1)} : </h4>
<h4 onClick={this.setMinutes} style={{display: 'inline'}}>{this.state.time.toLocaleTimeString().slice(2,4)} : </h4>
<h4 onClick={this.setSeconds} style={{display: 'inline'}}>{this.state.time.toLocaleTimeString().slice(5,8)}</h4>
<h4 style={{display: 'inline'}}>{this.state.time.toLocaleTimeString().slice(8,10)}</h4>
{/* Just to take care of the bottom margin of the border */}
<h1 style={{margin: '10px'}}></h1>
</div>
)
}
}
export default Clock
【问题讨论】: