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>

猜你喜欢

转载自blog.csdn.net/hahahahahahahaha__1/article/details/80707248