why should we use import React from 'react'

2019-07-16 05:58发布

问题:

This question already has an answer here:

  • Do I need to import React for stateless functional components? 2 answers

i am learning React js in case ii App.js module i have to import React because the render() method is used to convert JSX to dom elements how ever in Person.js we are creating a arrow function and we are exporting it so that it can be imported and used in the App modules render function how ever in App module we have React imported and it will convert the JSX in module person and gets rendered on DOM but when it throws an error when we remove the below code in Person.js

import React from 'react' in Person.js

it throws error

React' must be in scope when using JSX if we declare JSX in the methods (like render ) provided from React class it should give an error.

can someone please explain

i)why do we need to import react in Person.js?

ii)why was it throwing error when we remove the above code?

case i)

Person.js

 import React from 'react'

 const person = () => {
 return <p>This is person module used inside app module</p>
 };

 export default person

case ii)

App.js

import React, { Component } from 'react';
import './App.css'
import Person from './Person/Person'

class App extends Component {
render() {
return (
  <div className="App">
    <h1>this is app module and i am being used as the root component</h1>
     <Person/>
  </div>
);}}

export default App;

回答1:

If you give some JSX to Babel, you will see that JSX is just sugar for React.createElement calls. This is why we need to import React if we use JSX.

Input

<p>This is person module used inside app module</p>

Output

"use strict";

React.createElement(
  "p",
  null,
  "This is person module used inside app module"
);


回答2:

When you are trying to use jsx in your javascript file your normal compiler as well as even babel couldnot understand it. Although normal compiler never understand it. But anyhow you want to say your compiler I am providing you a jsx in the file.

import React from 'react';

Above is the way to instruct babel go on, its a easy task for you now.

<p>This is person module used inside app module</p>

Above is a jsx statment. So when ever you use it you will require React imported. Similarly we donot need it in actions, reducers and so on in many places because we dont have jsx there.