<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>React组件的生命周期</title>
<script type="text/javascript" src="react.js"></script>
<script type="text/javascript" src="react-dom.js"></script>
<script type="text/javascript" src="browser.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
var HelloMessage=React.createClass(
{
//1、创建阶段
getDefaultProps:function(){
//在创建类的时候被调用 this.props该组件的默认属性
console.log("getDefaultProps");
return {};
},
//2、实例化阶段
getInitialState:function(){
//初始化组件的state值,其返回值会赋值给组件的this.state属性
//获取this.state的默认值
console.log("getInitialState");
return {};
},
componentWillMount:function(){
//在render之前调用此方法
//业务逻辑的处理都应该放在这里,如对state的操作等
console.log("componentWillMount");
},
render:function(){
//根据state值,渲染并返回一个虚拟DOM
console.log("render");
return <h1 style={{color:'#ff0000',fontSize:'24px'}} >Hello {this.props.name}!我是中国梦苏</h1>;
//这是注释 React.createElement
},
componentDidMount:function(){
//该方便发生在render方法之后
//在该方法中,ReactJS会使用render方法返回的虚拟DOM对象来创建真实的DOM结构
//组件内部可以通过this.getDOMNode()来获取当前组件的节点
console.log("componentDidMount");
},
//3、更新阶段,主要发生在用户操作之后或父组件有更新的时候,此时会根据用户的操作行为进行相应的页面结构的调整
componentWillReceiveProps:function(){
//该方法发生在this.props被修改或父组件调用setProps()方法之后
//调用this.setState方法来完成对state的修改
console.log("componentWillRecieveProps");
},
shouldComponentUpdate:function() {
//用来拦截新的props或state,根据逻辑来判断
//是否需要更新
console.log("shouldComponentUpdate");
return true;
},
componentWillUpdate:function(){
//shouldComponentUpdate返回true的时候执行
//组件将更新
console.log("componentWillUpdate");
},
componentDidUpdate:function(){
//组件更新完毕,我们常在这里做一些DOM操作
console.log("componentDidUpdate");
},
//4、销毁阶段
componentWillUnmount:function(){
//销毁时被调用,通常做一些取消事件绑定、移除虚拟DOM中对应的组件数据结构、销毁一些无效的定时器等工作
console.log("componentWillUnmount");
}
}
);
ReactDOM.render(<HelloMessage name="React 语法基础8" /> ,document.getElementById('example'));
</script>
</body>
</html>
React组件的生命周期
最新推荐文章于 2024-08-04 13:48:08 发布