React VS ReactDom

在学 React 看资料和 Demo 时,遇到这样的代码:

// ES6
import React from 'react'
import ReactDOM from 'react-dom'

// CommonJS
const React = require('react')
const ReactDom = require('react-dom')

黑人问号

不要怕,其实是这样的:在 React v0.14 时,React被拆分为 reactreact-dom 两个包。如下:

  • react
    • React.createElement
    • React.createClass
    • React.Component
    • React.PropTypes
    • React.Children
  • react-dom
    • ReactDOM.render
    • ReactDOM.unmountComponentAtNode
    • ReactDOM.findDOMNode
    • server
      • ReactDOMServer.renderToString
      • ReactDOMServer.renderToStaticMarkup

按照官方的说法,这样做的原因是为了 React 早日一统江湖,跨平台地(isomorphic)分享组件代码。

As we look at packages like react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.

To make this more clear and to make it easier to build more environments that React can render to, we’re splitting the main react package into two: react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native. We don’t expect all the code in an app to be shared, but we want to be able to share the components that do behave the same across platforms.

Reference

为啥 React.ComponentReact.createClass 要多 bind(this)

对比 React.ComponentReact.createClass 相关的资料有很多:

其中最令我迷惑的就是 React.Component No Autobinding

黑人问号

这篇文章讲的超级棒!Why and how to bind methods in your React component classes?

简单来讲,对于 React.createClass 来说,render 的情况如下:

const obj = {
  name: 'react',
  render() {
    console.log(this.name)
  }
}

// onClick = this.clickHandler
obj.render() // 'react'

this 可以正确被绑定。

但是 React.Component 来讲,render 的情况如下:

const name = 'window'
const obj = {
  name: 'react',
  render() {
    console.log(this.name)
  }
}

// onClick = this.clickHandler
const f = obj.render
f() // 'window'