1、问题背景
利用React实现一个计时器的效果,改变时间为1s
2、实现源码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>React之简单入门实例(计时器)</title>
<link rel="stylesheet" href="css/base.css" />
<script type="text/javascript" src="js/react.js" ></script>
<script type="text/javascript" src="js/react-dom.js" ></script>
<script>
var ea = React.createClass({
render: function() {
var elapsed = Math.round(this.props.elapsed / 100);
var seconds = elapsed / 10 + (elapsed % 10 ? '' : '.0' );
var message = '开始计时:' + seconds + ' 秒';
return React.DOM.p(null, message);
}
});
var eaf = React.createFactory(ea);
var startTime = new Date().getTime();
setInterval(function() {
ReactDOM.render(
eaf({elapsed: new Date().getTime() - startTime}),document.getElementById('timer')
);
}, 1000);
</script>
</head>
<body>
<div id="timer"></div>
</body>
</html>
3、实现结果