why to import React

2019-04-19 10:52发布

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 ??

4条回答
我命由我不由天
2楼-- · 2019-04-19 11:20

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').

查看更多
欢心
3楼-- · 2019-04-19 11:31

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楼-- · 2019-04-19 11:42

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.

查看更多
趁早两清
5楼-- · 2019-04-19 11:45

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')
查看更多
登录 后发表回答