我想讓組件製成的時鐘反應。我希望來自不同組件的每個值。我得到的代碼:React JS時鐘組件
import React from 'react';
import ReactDOM from 'react-dom';
class ClockTimeHour extends React.Component{
render(){
return <h1>{this.props.date.getHours()}</h1>
}
}
class ClockTimeMinute extends React.Component{
render(){
return <h1>{this.props.date.getMinutes()}</h1>
}
}
class ClockTimeSecond extends React.Component{
render(){
return <h1>{this.props.date.getSeconds()}</h1>
}
}
class ClockDateYear extends React.Component{
render(){
return <h1>{this.props.date.getFullYear()}</h1>
}
}
class ClockDateMonth extends React.Component{
render(){
return <h1>{this.props.date.getMonth()}</h1>
}
}
class ClockDateDay extends React.Component{
render(){
return <h1>{this.props.date.getDate()}</h1>
}
}
class ClockTime extends React.Component{
render(){
return (
<div>
<ClockTimeHour date={this.state.now}/>
<ClockTimeMinute date={this.state.now}/>
<ClockTimeSecond date={this.state.now}/>
</div>
);
}
}
class ClockDate extends React.Component{
render(){
return (
<div>
<ClockDateYear date={this.state.now}/>
<ClockDateMonth date={this.state.now}/>
<ClockDateDay date={this.state.now}/>
</div>
);
}
}
class Clock extends React.Component{
constructor(props){
super(props)
this.state={
now: new Date()
}
}
componentDidMount() {
this.timerId=setInterval(()=>{
this.setState({ now : new Date() });
},1000);
}
render(){
return (
<div>
<ClockTime date={this.state.now}/>
<ClockDate date={this.state.now}/>
</div>
);
}
}
document.addEventListener('DOMContentLoaded', function(){
ReactDOM.render(
<Clock/>,
document.getElementById('app')
);
});
,當我運行它,我得到了:遺漏的類型錯誤:在ClockTime.render
無法讀取空的特性「現在」
您沒有設置組件ClockTime的狀態 –