React 官网列子学习

一个有状态的组件

除了接受输入数据(通过 this.props ),组件还可以保持内部状态数据(通过this.state )。当一个组件的状态数据的变化,展现的标记将被重新调用render() 更新。

先看结构,下面是hook函数

hook函数:<br>
最早是指windows 系统下提供的一种用来替换DOS 系统下的中断的系统机制;<br>
现在则是泛指,在对特定的系统事件进行hook 后,一旦发生已hook 事件,对该事件进行hook 的程序,就会收到系统的通知。这是程序就可以对该事件第一时间做出响应。

//Mounting 表示 React Components 被render 解析生成对应的DOM 节点并被插入浏览器的DOM 节点并被插入浏览器的DOM 结构的一个过程
//执行顺序看上图

var Timer = React.createClass({
//初始化state
  getInitialState: function() {
    return {secondsElapsed: 0};
  },
  tick: function() {
  //调用setState为secondsElapsed重新赋值,调用后会重新render
    this.setState({secondsElapsed: this.state.secondsElapsed + 1});
  },
  //react Components生命周期在render后调用
  componentDidMount: function() {
  //定时器更新
this.interval = setInterval(this.tick, 1000); }, //react Components生命周期在控件销毁时调用 componentWillUnmount: function() {
    //清除当前定时器 clearInterval(
this.interval); }, render: function() { return ( //输出当前secondsElapsed值 <div>Seconds Elapsed: {this.state.secondsElapsed}</div> ); } }); //mountNode,绑定到指定id上,一般这么写document.getElementById('app') React.render(<Timer />, mountNode);
原文地址:https://www.cnblogs.com/zyandroid/p/5460974.html