react---组件的生命周期

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src='react.js'></script>
	<script src='react-dom.js'></script>
	<script src='babel.min.js'></script>
</head>
<body>
	<div id='example'></div>
	<script type='text/babel'>
		/*创建组件*/
		class Temp extends React.Component{
			constructor(){
				super();
				this.state = {
					name:'world!'
				}
			}
			/*组件挂载前  此时访问不到元素,但是可以访问属性和状态*/
			componentWillMount(){
				console.log('组件挂载前!');
				console.log(this.state.name);/*world!*/
				console.log(this.props.mood);/*good*/
				console.log(document.getElementById('con'));/*null*/
			}
			/*组件挂在后 可以访问元素,属性,状态*/
			componentDidMount(){
				console.log('组件挂载后!');
				console.log(this.state.name);/*world!*/
				console.log(this.props.mood);/*good*/
				console.log(document.getElementById('con'));/*div标签*/
			}
			/*组件更新前*/
			componentWillUpdate(){
				console.log('组件更新前!');
			}
			/*组件更新后*/
			componentDidUpdate(){
				console.log('组件更新后!');
			}
			/*组件卸载前*/
			componentWillUnmount(){
				console.log('组件卸载前!');
			}
			change(e){
				this.setState({
					name:'lily'
				});
				/*React中的事件对象已经经过包装,故原生的事件对象的取消冒泡的方式已经不再适用*/
				/*React中取消事件冒泡*/
				e.nativeEvent.stopImmediatePropagation();
			}
			/*返回JSX*/			
			render(){
				return (
					<div id='con'>
						<h1>hello {this.state.name}!</h1>	
						<h3>my mood is {this.props.mood}!</h3>
						<input type="button" value='change' onClick={this.change.bind(this)}/>
					</div>
				);
			}
		}
		/*组件渲染*/
		ReactDOM.render(
			<Temp mood='good'/>,
			document.getElementById('example')
		);
		/*此时由于事件冒泡的原因,可能使我们点击change按钮就会让组件卸载,故我们要在按钮的change事件中取消事件冒泡*/
		document.onclick = function(){
			/*要想卸载某个组件只能通过重新渲染*/
			ReactDOM.render(
				<h1>hello!!!</h1>,
				document.getElementById('example')
			);
		}
	</script>
	
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值