Created
March 2, 2017 10:51
-
-
Save Ami777/0739c6023ce8af48ad335c8aa545e290 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
document.addEventListener('DOMContentLoaded', function(){ | |
class TrafficLights extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
step: 1, | |
}; | |
} | |
changeLight(){ | |
const newStep = this.state.step === 4 ? 1 : this.state.step + 1; | |
this.setState({ | |
step : newStep, | |
}); | |
this.makeTimeout(); | |
} | |
makeTimeout(){ | |
let sec; | |
switch( this.state.step ){ | |
case 1: | |
sec = this.props.redTime; | |
break; | |
case 2: | |
case 4: | |
sec = this.props.yellowTime; | |
break; | |
case 3: | |
sec = this.props.greenTime; | |
break; | |
} | |
this.timeoutId = setTimeout(() => { | |
this.changeLight(); | |
}, sec * 1000); | |
} | |
componentDidMount() { | |
this.makeTimeout(); | |
} | |
componentWillUnmount() { | |
clearTimeout( this.timeoutId ); | |
} | |
render() { | |
let redLightColor = 'black'; | |
let orangeLightColor = 'black'; | |
let greenLightColor = 'black'; | |
switch( this.state.step ){ | |
case 1: | |
redLightColor = 'red'; | |
break; | |
case 2: | |
redLightColor = 'red'; | |
orangeLightColor = 'yellow'; | |
break; | |
case 3: | |
greenLightColor = 'green'; | |
break; | |
case 4: | |
orangeLightColor = 'yellow'; | |
break; | |
} | |
return <div> | |
<div> | |
<div style={{borderRadius:'50%',height:'100px',width:'100px',backgroundColor:redLightColor}} /> | |
</div> | |
<div> | |
<div style={{borderRadius:'50%',height:'100px',width:'100px',backgroundColor:orangeLightColor}} /> | |
</div> | |
<div> | |
<div style={{borderRadius:'50%',height:'100px',width:'100px',backgroundColor:greenLightColor}} /> | |
</div> | |
</div> | |
} | |
} | |
class App extends React.Component { | |
render(){ | |
return <TrafficLights redTime={0.5} yellowTime={0.5} greenTime={1.5} />; | |
} | |
} | |
ReactDOM.render( | |
<App />, | |
document.getElementById('app') | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment