我想使时钟由组件组成。我希望每个值都来自不同的组件。我得到的代码:
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')
);
});
当我运行它时,我得到了:Uncaught TypeError:在ClockTime.render处无法读取null的属性“ now”
最佳答案
您没有为您提到的组件设置状态,但是您通过它的道具以date
此处<ClockTime date={this.state.now}/>
的方式进行传递,因此我假设您可能希望更改为:
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 ClockTime extends React.Component{
render(){
return (
<div>
<ClockTimeHour date={this.props.date}/>
<ClockTimeMinute date={this.props.date}/>
<ClockTimeSecond date={this.props.date}/>
</div>
);
}
}
您可以找到使用代码的here工作示例,但要应用我已提出的更改。
关于javascript - React JS Clock Compo,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43527491/