在React目前来讲,组件的创建主要分成了三种方式:

  • 函数式创建
  • 通过 React.createClass 方法创建
  • 继承 React.Component 创建

函数式创建

  1. function HelloComponent(props, /* context */) {
  2. return <div>Hello {props.name}</div>
  3. }

通过 React.createClass 创建

React.createClass是react刚开始推荐的创建组件的方式,目前这种创建方式已经不怎么用了
像上述通过函数式创建的组件的方式,最终会通过babel转化成React.createClass这种形式,转化成如下:

  1. function HelloComponent(props) /* context */{
  2. return React.createElement(
  3. "div",
  4. null,
  5. "Hello ",
  6. props.name
  7. );
  8. }

由于此种方式过于复杂,基本上已经不使用了

继承 React.Component 创建

react hooks出来之前,有状态的组件只能通过继承React.Component这种形式进行创建
有状态的组件也就是组件内部存在维护的数据,在类创建的方式中通过this.state进行访问
当调用this.setState修改组件的状态时,组价会再次会调用render()方法进行重新渲染
通过继承React.Component创建一个时钟示例如下:

  1. class Timer extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = { seconds: 0 };
  5. }
  6. tick() {
  7. this.setState(state => ({
  8. seconds: state.seconds + 1
  9. }));
  10. }
  11. componentDidMount() {
  12. this.interval = setInterval(() => this.tick(), 1000);
  13. }
  14. componentWillUnmount() {
  15. clearInterval(this.interval);
  16. }
  17. render() {
  18. return (
  19. <div>
  20. Seconds: {this.state.seconds}
  21. </div>
  22. );
  23. }
  24. }

区别

由于React.createClass 创建的方式过于冗杂,并不建议使用
而像函数式创建和类组件创建的区别主要在于需要创建的组件是否需要为有状态组件:

  • 对于一些无状态的组件创建,建议使用函数式创建的方式
  • 由于react hooks的出现,函数式组件创建的组件通过使用hooks方法也能使之成为有状态组件,再加上目前推崇函数式编程,所以这里建议都使用函数式的方式来创建组件

在考虑组件的选择原则上,能用无状态组件则用无状态组件