1. 程式人生 > >React.js 時間元件 + 元件生命週期(更新模擬)

React.js 時間元件 + 元件生命週期(更新模擬)

React是用於構建使用者介面的 JavaScript 庫,React 元件使用一個名為 render() 的方法, 接收資料作為輸入,輸出頁面中對應展示的內容。
React除了可以使用外部傳入的資料以外 (通過 this.props 訪問傳入資料), 元件還可以擁有其內部的狀態資料 (通過 this.state 訪問狀態資料)。 當元件的狀態資料改變時, 
元件會呼叫 render() 方法重新渲染。
效果圖如下,基本沒寫樣式,不是很美觀!
例項模擬:
<style>
	.list{
		list-style:none;
	}
	#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>