[进阶指南] 不使用 ES6 开发 React( Day27 )

如果不使用 ES6 的 Class,则可以考虑用 create-react-class 。

var HelloCreateClass = createReactClass({
  render: function() {
    return <h1>Hello, {this.props.greeting}</h1>;
  }
});

使用 create-react-class 与 Class 的差别

  • 宣告预设 Props
  • 设定初始 state 使用 getInitialState
  • 自动绑定 event this
  • 支援 Mixin //副作用效果高,不建议使用

以下改写 Class Component <Clock> 的例子:

var Clock = createReactClass({
  getInitialState: function() { //设定 State
    return {
      date: new Date(),
      timerID: ''
    };
  },
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  },
  componentWillUnmount() {
    clearInterval(this.timerID);
  },
  tick() {
    this.setState({
      date: new Date()
    });
  },
  start() { //不需要写 this.start = this.start.bind(this) 就自动绑定
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  },
  stop() {
    clearInterval(this.timerID);
  },
  render: function() {
    return <div>
        <h1>Hello, Create Class!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
        <button onClick={this.start}> Start</button><button onClick={this.stop}> Stop</button>
      </div>;
  }
});

使用 Mixin 改写

ES6 并没有支援任何 mixin 语法。因此当你在 React 中使用 ES6 class 时也不支援使用 mixin。
我们也发现在程序中使用 mixin 会造成很多问题,因此不建议在新的程序码中使用 mixin。
此段落内容仅供参考。 - React Document

  • Mixins 引入依赖 (Mixins introduce implicit dependencies)
  • Mixins 造成命名冲突 (Mixins cause name clashes)
  • Mixins 造成滚雪球的复杂性 (Mixins cause snowballing complexity)

下面将 setinterval 相关功能拆出 Mixin 的功能作为例子:

var SetIntervalMixin = {
  getInitialState: function() { //设定 State
    return {
      date: new Date(),
      timerID: ''
    };
  },
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  },
  componentWillUnmount() {
    clearInterval(this.timerID);
  },
  tick() {
    this.setState({
      date: new Date()
    });
  },
};

var Clock = createReactClass({
mixins: [SetIntervalMixin], // 使用 mixin
//略
});

Codepen 完整程序

以上今天。

参考资料:
https://zh-hant.reactjs.org/docs/react-without-es6.html
https://zh-hant.reactjs.org/blog/2016/07/13/mixins-considered-harmful.html


<<:  Day 27 -资料库应用小程序 首页功能(内涵程序码)

>>:  Day 26 设定 Redux 环境

Day 6 作业系统

今天谈一下即时作业系统(Real-time operating system, RTOS),根据维基...

Day 11 - 阵列 a

简介- 为什麽要使用阵列? 当我们想要宣告一个变数的时候,我们可以一次叫一个 像是这样 #inclu...

[Day 15] 将专案放上GitHub

今天来把专案上到GitHub啦~ 老实说Git就是那种学校没教,但是你工作又90%会用到的重要东东 ...

30天学会C语言: Day 4-输入个资料怎麽那麽麻烦啦

运算子(Operator) 在程序码中代表运算的符号,参与运算的数值或变数称为运算元(Operand...