1. 程式人生 > >React學習筆記(五)封裝時鐘

React學習筆記(五)封裝時鐘

//封裝時鐘
//原時鐘程式碼
function Clock(clock) {
    return (
        <div>
            <h1>Hello, world!</h1>
            <h2>It is {clock.date.toLocaleTimeString()}.</h2>
        </div>
);
}

function tick() {
    ReactDOM.render(
        <Clock date={new Date()} />,
document
.getElementById('root') ); } setInterval(tick, 1000); //將函式轉換為類 //建立一個名稱拓展為React.Component的ES6類 class Clock extends React.Component{ //新增一個類建構函式來初始化狀態this.state constructor(clock){ //noinspection JSAnnotator super(clock) this.state = {date:new Date()} } //生命週期鉤子 //每當Clock元件第一次載入到DOM中的時候,我們都想生成定時器,這在React中被稱為掛載
componentDidMount(){ this.timerID = setInterval( () => this.tick(), 1000 ) } //同樣,每當Clock生成的這個DOM被移除的時候,我們也會想要清除定時器,這在React中被稱為解除安裝。 componentWillUnMount(){ clearInterval(this.timerID) } tick(){ //setState更新元件區域性狀態 this.setState({ date:new
Date() }) } //建立一個叫做render()的方法 render(){ //將函式體寫入到render()方法中 return( // 在render()方法中,使用this.clock替換clock,刪除剩餘的空函式宣告 <div> <h1>hello,world</h1> {/*<h2>現在是{this.clock.date.toLocaleString()}</h2>*/} {/*在render()方法中使用this.state.date替代this.clock.date*/} <h2>現在是{this.state.date.toLocaleString()}</h2> </div> ) } } ReactDOM.render( <Clock/>, document.getElementById('root') )