iT邦幫忙

2021 iThome 鐵人賽

DAY 27
0
自我挑戰組

React 學習之路系列 第 27

[進階指南] 不使用 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


上一篇
[進階指南] Portal( Day26 )
下一篇
[進階指南] 不使用 JSX 開發 React( Day28 )
系列文
React 學習之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言