React class clock代码实例
<html>
<head>
<title>Document</title>
<script src="../react.js"></script>
<script src="../react-dom.js"></script>
<script src="https://cdn.bootcss.com/babel-core/5.8.38/browser.min.js"></script>
</head>
<body>
<p id="demo"></p>
<script type="text/babel">
function FormatedDate(props) {
return <h2>It is {props.date.toLocaleTimeString()}.</h2>
}
class Clock extends React.Component{
constructor(props) {
super(props)
this.state = {date: new Date()}
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
)
}
componentWillUnmount() {
clearInterval(this.timerID)
}
tick() {
this.setState({
date: new Date()
})
}
render() {
return (
<FormatedDate date={this.state.date} />
)
}
}
ReactDOM.render(
<Clock />,
document.getElementById("demo")
)
</script>
</body>
</html>