why to import React

2019-04-19 10:47发布

问题:

I have code which works only after importing React but I'm not using React anywhere I'm using reactDom instead

import ReactDOM from 'react-dom'
import React, {Component} from 'react'

class App extends Component {
  render () {
    return (
      <div>comp </div>
    )
  }
}

//ReactDOM.render(<App/>, document.getElementById('root'))
ReactDOM.render(<div>sv</div>, document.getElementById('root'))

why its require to import React ??

回答1:

Although you don't explicitly use the React instance you've imported, JSX is transpiled to React.createElement() call, which uses it.

In your example, <div>comp </div> is transpiled by Babel to React.createElement('div', null, 'comp').



回答2:

React import is required because the following JSX code:-

(
   <div>comp </div>
)

gets transpiled to

React.createElement(
  "div",
  null,
  "comp "
);

This is the reason you need to import React; I hope that answers your question.

You can always refer to https://babeljs.io to understand what get's converted to what.



回答3:

This is a really interesting question, since you're right that the code doesn't look like it's using React, but it's being tricky.

Any time you use the shorthand <Component /> code what's actually happening is the JSX is transpiled by Babel into something that is regular Javascript.

<Component/>
// Is turned into
React.createElement(...)

Therefore the code does indeed need React to be imported, although it's not obvious to the reader



回答4:

I used to think that if ReactDOM uses React then it will take care of importing it. But that's not the case. After JSX in your source code is transformed it is evident that its explicitly using the React package. And hence it is required.

React.createElement('div', null, 'comp')