React.JS生命週期函數

在這裏插入圖片描述
在這裏插入圖片描述
執行結果如下
在這裏插入圖片描述

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>

<body>

    <div id="example"></div>
    <script type="text/babel">
        //react推薦使用內聯樣式
        var myStyle = {
            fontSize: 30,
            fontFamily: 'Monospace',
            color: '#FF0000'
        };
        var arr = [
            <h1> JSX允許在模板中插入數組 </h1>,
            <h2> 數組會自動展開所有成員 </h2>,
            <h2> 就像這樣 </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 (
                    <div>
                        <h1>Hello,World!</h1>
                        {/*爲什麼要加this.props?*/}
                        <h2>Now: {this.state.date.toLocaleString()}</h2>
                    </div>
                );
            }
        }//這樣就封裝了一個組件
        class MyStyle extends React.Component {
            render() {
                return <h1 style={myStyle}>This is myStyle.</h1>;
            }
        }
        class MyArray extends React.Component {
            render() {
                return <div> {arr} </div>
            }
        }
        function App(props) {
            return (
                <div>
                    <Clock />
                    <MyStyle myStyle={myStyle} />
                    <MyArray arr={arr} />
                </div>
            )
        }
        const element = <App />

        ReactDOM.render(
            element,
            document.getElementById('example')
        );

    </script>

</body>
</html>

執行順序:

Created with Raphaël 2.2.0開始<Clock />被傳遞給React.render(),React調用Clock組件的構造函數React調用Clock組件的render()方法將當前的時間顯示在屏幕上React 調用 componentDidMount() 生命週期鉤子定時器被設置,每秒鐘調用一次tick函數 即調用setState改變date的值爲當前時間一旦 Clock 組件被從 DOM 中移除,React 會調用 componentWillUnmount() 這個鉤子函數,定時器也就會被清除。結束

效果:(不會截gif圖)
在這裏插入圖片描述

關於setState可參考:https://segmentfault.com/a/1190000015463599?utm_source=tag-newest
本文參考:
https://www.runoob.com/react/react-state.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章