React组件之Clock

2,148 阅读2分钟

这个例子是React官方文档里面的,代码也在CodePen,例子非常简单,展示了React组件开发的基本过程,这里将这个例子进行分析记录,当做学习笔记吧!首先看代码:

//HTML
 <div id="root">
    <!-- This element's contents will be replaced with your component. -->
</div>

//JS
function FormattedDate(props) {
  return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <FormattedDate date={this.state.date} />
      </div>
    );
  }
}

function App() {
  return (
    <div>
      <Clock />
      <Clock />
      <Clock />
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

程序的运行过程:

1、在html里面定义一个div,id为root

2、 调用ReactDOM.render使用App渲染id为root的div,这里会调用函数App

3、函数App返回的是什么呢?不是字符串,也不是HTML,而是JSX,JSX是JavaScript语法的扩展,Babel会将JSX编译成React.createElement()的调用,这里可以简单看成返回界面布局就行了

4、在函数App返回的布局中,有三个Clock组件,Clock组件继承React.Component,当被传入ReactDOM.render中后,会调用Clock构造方法

5、在Clock构造方法可以接收一个props, 它来保存组件的组件的属性,这里并没有传入任何属性值,在构造方法里面初始化组件的状态state,给状态设置了date字段

6、接下来会调用Clock的render方法来渲染组件,render方法也是返回了JSX,里面有Hello World的标题,并且调用FormattedDate函数,传入参数date,返回时间的JSX,在FormattedDate函数里通过props.date获取传入的date

7、这时候就已经可以看到三个Clock显示时间了

8、那时间怎么自动更新的呢?当Clock被插入DOM时,会触发componentDidMount,当Clock从DOM移除时,会触发componentWillUnmount,所以在componentDidMount调用时开始定时更新,在componentWillUnmount关闭定时更新

9、定时更新会调用tick方法,tick方法调用setState来更新date字段

10、setState方法会触发render方法的重新调用,进而更新时间

由于笔者之前是做移动端开发,React的组件的概念跟iOS和Android的View的概念基本一致,甚至一些方法可以对应的上,如componentDidMount和componentWillUnmount可对应Android View中的onAttachedToWindow和onDetachedFromWindow, Clock中的render可对应Android View中的onDraw。可以看出来编程理念都是大同小异。组件化实际上就是模块化,提高了代码的复用性和可维护性。