React文档源码
class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; // 为了在回调中使用 `this`,这个绑定是必不可少的 this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(state => ({ isToggleOn: !state.isToggleOn })); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); }}ReactDOM.render( <Toggle />, document.getElementById('root'));
为什么要用bind重新绑定?
首先一点,React这是使用的ES6的 class
,它只是一种语法糖(只要它能实现的,ES5也能实现)。
而使用 class 创建的对象,在没有通过 new
关键字去实例化的之前,除 constructor()
外,它的内部方法this是无绑定状态的。
也就是说上面的代码,handleClick
方法如果不做绑定,那么这个方法的 this
会指向 undefined
class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; // 为了在回调中使用 `this`,这个绑定是必不可少的 // this.handleClick = this.handleClick.bind(this); } handleClick() { console.log(this) // 输出是 undefined } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); }}ReactDOM.render( <Toggle />, document.getElementById('root'));
那为什么 render
函数里面的 this
指向的不是 undefined
解释:JSX代码经过 Babel 编译之后变成 React 的表达式,这个表达式在render函数被调用的时候通过 React 的 createElement
方法生成一个element,在这个方法中,this指向了被创建的类(也就是相应的React组件)。
看看上面那段JSX代码转换成 JS 代码是什么样子
主要看 _createClass
方法,第一个参数是被创建的类,第二个参数是一个数组,数组里面是这个被创建类中的方法。
很显然,代码中 handleClick
输出的this, 肯定是undefined。
而 render
方法返回的是 React.createElement
,在这个方法中,this被指向了 _createClass
方法的第一个参数,也就是 Toggle
。
附:经过 Babel 编译之后 React 表达式的完整源码
"use strict";function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } }function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }var Toggle = /*#__PURE__*/function (_React$Component) { _inherits(Toggle, _React$Component); var _super = _createSuper(Toggle); function Toggle(props) { var _this; _classCallCheck(this, Toggle); _this = _super.call(this, props); _this.state = { isToggleOn: true }; // 为了在回调中使用 `this`,这个绑定是必不可少的 // this.handleClick = this.handleClick.bind(this); return _this; } _createClass(Toggle, [{ key: "handleClick", value: function handleClick() { console.log(this); // 输出是 undefined } }, { key: "render", value: function render() { return /*#__PURE__*/React.createElement("button", { onClick: this.handleClick }, this.state.isToggleOn ? 'ON' : 'OFF'); } }]); return Toggle;}(React.Component);