2017-04-20 101 views
1

我想讓組件製成的時鐘反應。我希望來自不同組件的每個值。我得到的代碼: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

無法讀取空的特性「現在」
+1

您沒有設置組件ClockTime的狀態 –

回答

1

您沒有設置狀態的組件,您提及,但你是通過它的道具作爲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一個工作示例,使用你的代碼,但應用我已經分割的更改。

+0

它仍然不起作用。沒有'date'爲空 – zamf

+0

它發生了什麼?您還必須將相同的解決方案應用於ClockDate –

+0

我已更改它的ic ClockTime,ClockDate和時鐘。現在它給了我:在ClockTime.render – zamf