React小Demo2:制作快闪文字

本文深入探讨了React组件的生命周期,包括Mounting、Updating和Unmounting三个阶段,以及每个阶段的重要函数,如componentDidMount和componentWillUnmount。通过一个具体示例,展示了如何使用这些生命周期方法来实现动态更新组件的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <script src="build/react.js"></script>
    	<script src="build/react-dom.js"></script>
    	<script src="build/browser.min.js"></script>
    	<script src="build/jquery.min.js"></script>
    </head>
    <body>
    	<div id="example">aaa</div>
    </body>
    <script type="text/babel">
    	var Note=React.createClass({
    		//设定默认值
    		getDefaultProps:function(){
    			return {title:'Hello,World!'};
    		},
    		//设置初始状态或样式
    		getInitialState:function(){
    			return {
    				opacity:1.0,
    				color:'#'+parseInt(Math.random()*1000000)
    			};
    		},
    		//组件的生命周期
			// Mounting:已插入真实DOM
			// Updating:正在被重新渲染
			// Unmounting:已移出真实DOM
			// will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数。
			// componentWillMount()
			//  componentDidMount()
			// componentWillUpdate(object nextProps,object nextState)
			// componentDidUpdate(object preProps,object preState)
			// componentWillUnmount()
			// 另外两种特殊状态处理函数
			// componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用
			// shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用
			componentDidMount:function(){
				this.timer=setInterval(function(){
					var opacity=this.state.opacity;
					var	color=this.state.color;
					opacity-=1;
					if(opacity<0){
						opacity=1.0;
						color='#'+parseInt(Math.random()*1000000)
					}
					this.setState({
						opacity:opacity,
						color:color
					})
				}.bind(this),100)
			},
			render:function(){
				return (
					<h1 style={{opacity:this.state.opacity,color:this.state.color}}>
						{this.props.title}
					</h1>
				)
			}
    	});
    	ReactDOM.render(
    		<Note/>,
    		document.getElementById('example'))
    </script>
</html>

转载于:https://my.oschina.net/u/3095670/blog/995246

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值