生命周期就是勾子函数:React组件中包含一系列勾子函数(生命周期回调函数), 会在特定的时刻调用。
1.卸载组件
一旦点击按钮就自动删除组件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script src="./react-resource/babel.min.js"></script> <script src="./react-resource/prop-types.js"></script> <script type="text/babel"> class Login extends React.Component{ death=()=>{ ReactDOM.unmountComponentAtNode(document.getElementById("test")) } render(){ return ( <div> <h1>爱娟宝</h1> <button onClick={this.death}>登录</button> </div> ) } } ReactDOM.render(<Login/>,document.getElementById("test")); </script> </body> </html>
2.综合代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script src="./react-resource/babel.min.js"></script> <script src="./react-resource/prop-types.js"></script> <script type="text/babel"> class Login extends React.Component{ state={opacity:1} death=()=>{ ReactDOM.unmountComponentAtNode(document.getElementById("test"))//卸载组件 } componentDidMount(){ //组件挂载完毕 this.timer=setInterval(()=>{ let {opacity}=this.state; opacity-=0.1; if(opacity<=0) opacity=1; this.setState({opacity}) },200) } componentWillUnmount(){ //组件将要卸载 clearInterval(ths.timer) } //初始化渲染,状态更新之后 render(){ return ( <div> <h1 style={{opacity:this.state.opacity}}>爱娟宝</h1> <button onClick={this.death}>登录</button> </div> ) } } ReactDOM.render(<Login/>,document.getElementById("test")); </script> </body> </html>