<!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>
原文地址:https://www.cnblogs.com/zhanzhuang/p/10716482.html
时间: 2024-10-28 03:28:58