2017-04-20 3 views
1

반응으로 구성 요소의 시계로 만들고 싶습니다. 각기 다른 구성 요소의 가치를 원합니다. 그 코드를 가지고 :React JS clock compo

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') 
    ); 
}); 

을 내가 그것을 실행하고 때 나는 가지고 : catch되지 않은 형식 오류를 : ClockTime.render

에 널 (null)의 '지금'속성을 읽을 수 없습니다 당신은 구성 요소의 상태를 설정하지 않는
+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

의 상태를 설정하지 않습니다. 여전히 작동하지 않습니다. '날짜'가 없습니다. – zamf

+0

어디에서 발생 했습니까? ClockDate에도 동일한 솔루션을 적용해야합니다 –

+0

ClockTime, ClockDate 및 Clock을 변경했습니다. 이제 나에게 준다 : null의 속성 'date'을 읽지 못한다. ClockTime.render에서 – zamf