1. 程式人生 > >14_組件_生命周期

14_組件_生命周期

cit func bind doc lang urn aci 按鈕 per

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="example"></div>
<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript"
src="../js/react-dom.development.js"></script> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel"> /* * 需求:自定義組件 * 1.讓指定的文本做顯示/隱藏的動畫 * 2.切換時間為2S * 3.點擊按鈕從界面中移除組件頁面 * */ // 創建虛擬dom class Life extends React.Component { constructor(props) { super(props);
//初始化狀態 this.state = { opacity: 1 } } distoryComponent() { ReactDOM.unmountComponentAtNode(document.getElementById(example)); } componentDidMount() { //啟動循環定時器 this.IntervalId = setInterval(
function () { console.log(定時器執行......) let {opacity} = this.state opacity -= 0.1 if (opacity <= 0) { opacity = 1 } this.setState({opacity}) }.bind(this), 200) } componentWillUnmount() { //清理定時器 clearInterval(this.IntervalId) } render() { const {opacity} = this.state return ( <div> <h2 style={{opacity}}>{this.props.msg}</h2> <button onClick={this.distoryComponent}>不活了</button> </div> ); } } // 渲染虛擬dom ReactDOM.render(<Life msg="react太難了!"/>, document.getElementById(‘example‘)) </script> </body> </html>

14_組件_生命周期