为什么我们应该使用 import React from 'react' [英] why should we use import React from 'react'

查看:28
本文介绍了为什么我们应该使用 import React from 'react'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在case ii App.js 模块中学习React js 我必须导入React 因为render() 方法用于将JSX 转换为dom 元素在 Person.js 中,我们正在创建一个箭头函数并导出它,以便它可以在 App 模块的渲染函数中导入和使用并在 DOM 上呈现,但是当我们在 Person.js 中删除以下代码时抛出错误

从 Person.js 中的 'react' 导入 React

它抛出错误

使用 JSX 时,React' 必须在范围内 如果我们在 React 类提供的方法(如 render )中声明 JSX,它应该会给出错误.

谁能解释一下

i) 为什么我们需要在 Person.js 中导入 react?

ii)为什么删除上面的代码会报错?

情况一)

<块引用>

Person.js

 从 'react' 导入 Reactconst 人 = () =>{return <p>这是在应用模块中使用的person模块</p>};导出默认人

情况二)

<块引用>

App.js

import React, { Component } from 'react';导入'./App.css'从'./Person/Person'导入人类 App 扩展组件 {使成为() {返回 (<div className="应用程序"><h1>这是应用模块,我被用作根组件</h1><人/>

);}}导出默认应用程序;

解决方案

如果你给 Babel 一些 JSX,你会看到 JSX 只是 React.createElement 调用的糖一>.这就是为什么我们在使用 JSX 时需要导入 React.

输入

<p>这是应用模块内部使用的person模块</p>

输出

/*#__PURE__*/React.createElement("p", null, "This is person module used in inside app module");

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;

解决方案

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

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

这篇关于为什么我们应该使用 import React from 'react'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆