在 React.Component 中如何優雅的綁定函數的 context

在 stub Component 的一個方法時,發現這個方法沒在 prototype 上。研究了下編譯后代碼發現出一些貓膩,同時也引起思考:對于 React.Component 方法,如何優雅的去綁定 this。

  1. 問題現象
class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.method1 = this.method1.bind(this);
  }
  method1() {}
  method2 = () => {};
}

method1method2,分別使用 bind函數箭頭函數 兩種方式綁定 this
雖然在程序運行時大多數場景沒有問題,而且經常會使用箭頭函數綁定。但是這兩種聲明方式還是有差異的。

  1. 查找根因

使用官網的 create-react-app 轉換代碼發現,在 Demo.prototype 上只有 method1 沒有 method2

var Demo = function (_React$Component) {
  _inherits(Demo, _React$Component);
  function Demo(props) {
    _classCallCheck(this, Demo);
    var _this = _possibleConstructorReturn(this, (Demo.__proto__ || Object.getPrototypeOf(Demo)).call(this, props));
    _this.method2 = function () {};
    _this.method1 = _this.method1.bind(_this);
    return _this;
  }
  _createClass(Demo, [{
    key: 'method1',
    value: function method1() {}
  }]);
  return Demo;
}(__WEBPACK_IMPORTED_MODULE_0_react___default.a.Component);

method2是在Demo的構造方法內動態添加的;而method1通過_createClass方法被聲明被聲明在prototype上。
_createClass內部一段代碼如下

if (protoProps) defineProperties(Constructor.prototype, protoProps);
  1. 疑問:那種好?

ES2015的 class 只是一個語法糖而已,最終還是通過原型等方式實現。所以方法使用prototype方式聲明會更好些。
同時也意味著需要使用 bind方法綁定this

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容