React.js 时间组件 + 组件生命周期(更新模拟)

React是用于构建用户界面的 JavaScript 库,React 组件使用一个名为 render() 的方法, 接收数据作为输入,输出页面中对应展示的内容。
React除了可以使用外部传入的数据以外 (通过 this.props 访问传入数据), 组件还可以拥有其内部的状态数据 (通过 this.state 访问状态数据)。 当组件的状态数据改变时, 
组件会调用 render() 方法重新渲染。
效果图如下,基本没写样式,不是很美观!
实例模拟:
<style>
#app{
  width:80%;
  margin:0 auto;
  text-align:center;
  font-size:50px;
  font-weight:bold;
  color:black;
}
</style>
<script type="text/babel">
	class Comp extends React.Component{
		//构造函数 构造函数是在整个类中未初始化中执行的
		constructor(...args){  //构造函数名
		super(...args);//超类。
		this.state={h:'0',m:'0',s:'0'};
		var that=this;
		 setInterval(function(){
			that.fn()
		},1000)
	}
	componentDidMount(){
	  this.fn();
	}
	componentWillUpdate(){
      console.log("更新之前");
	}
	componentDidUpdate(){
      console.log("更新之后");
	}
	fn(){
	//传json
		var D=new Date();
		this.setState({h:D.getHours(),m:D.getMinutes(),s:D.getSeconds()})
	}
	render(){
	  return <div>
            <span>{this.state.h}:</span>
		   <span>{this.state.m}:</span>
		    <span>{this.state.s}</span>
		   </div>;
	}
   }
   window.onload=function(){
        var time=document.getElementById('app');
	ReactDOM.render(<Comp/>,time);
   }	    
</script>  

<div id="app"></div>
posted on 2018-11-17 16:45  (代码小工)  阅读(632)  评论(0编辑  收藏  举报