<!DOCTYPE html>
<html>
<head>
<script src="../build/react.js"></script>
<script src="../build/react-dom.js"></script>
<script src="../build/browser.min.js"></script>
</head>
<body>
<div id="div1"></div>
<script type="text/babel">
var HelloMessage = React.createClass({
getInitialState:function()
{
return { h:0, m:0, s:0 }
},
componentDidMount:function(){
var _this=this;
setInterval(function(){
_this.handleClick();
},1000)},
handleClick: function() {
var time=new Date();
this.setState(
{
h:time.getHours(),
m:time.getMinutes(),
s:time.getSeconds()
}
)
},
render: function() {
return <div>
<span>{this.state.h}:</span>
<span>{this.state.m}:</span>
<span>{this.state.s}</span>
</div>;
}
});
ReactDOM.render(
<HelloMessage />,
document.getElementById('div1'));
</script>
</body>
</html>
操作步骤:
1. getInitialState 初始化变量 h,m,s
2. handleClick 用函数来处理 this.setState () h,m, s
3. 将this.state.h,ms给render做渲染
4. componentDidMount
我们来快速回顾一下该过程,以及调用方法的顺序:
- 当 < HelloMessage /> 被传入 ReactDOM.render() 时, React 会调用 getInitialState函数。 因为 HelloMessage 要显示的是当前时间,所以它将使用包含当前时间的对象来初始化 this.state 。我们稍后会更新此状态。
- 然后 React 调用了 HelloMessage 组件的 render() 方法。 React 从该方法返回内容中得到要显示在屏幕上的内容。然后,React 然后更新 DOM 以匹配 HelloMessage 的渲染输出。
- 当 HelloMessage 输出被插入到 DOM 中时,React 调用 componentDidMount() 生命周期钩子。在该方法中,HelloMessage 组件请求浏览器设置一个定时器来一次调用 handleClick()。
- 浏览器会每隔一秒调用一次 handleClick()方法。在该方法中, Clock 组件通过 setState() 方法并传递一个包含当前时间的对象来安排一个 UI 的更新。通过 setState(), React 得知了组件 state(状态)的变化, 随即再次调用 render() 方法,获取了当前应该显示的内容。 这次,render() 方法中的 this.state.date 的值已经发生了改变, 从而,其输出的内容也随之改变。React 于是据此对 DOM 进行更新。
组件的生命周期分成三个状态:
名称 | 解释 |
---|---|
Mounting | 已插入真实 DOM |
Updating | 正在被重新渲染 |
Unmounting | 已移出真实 DOM |
React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数。
名称 | 解释 |
---|---|
componentWillMount() | 创建之前 |
componentDidMount() | 创建之后 |
componentWillUpdate(object nextProps, object nextState) | 更新之前 |
componentDidUpdate(object nextProps, object nextState) | 更新之后 |
componentWillUnmount() | 卸载之后 |
此外,React 还提供两种特殊状态的处理函数。
名称 | 解释 |
---|---|
componentWillReceiveProps(object nextProps) | 已加载组件收到新的参数时调用 |
shouldComponentUpdate(object nextProps, object nextState) | 组件判断是否重新渲染时调用 |