【问题标题】:why should we use import React from 'react' [duplicate]为什么我们应该使用 import React from 'react' [重复]
【发布时间】:2018-12-25 14:08:15
【问题描述】:

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

import React from 'react' in Person.js

报错

使用 JSX 时,React' 必须在作用域内如果我们在 React 类提供的方法(如 render )中声明 JSX,它应该会报错。

谁能解释一下

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

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

案例一)

Person.js

 import React from 'react'

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

 export default person

案例二)

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;

【问题讨论】:

  • 谢谢!。你能解释一下编译器是如何理解 JSX 在 Person.js 中使用的吗
  • 静态分析允许 Babel 检测 JSX(通过一些插件)。然后它使用更多插件来实际分解它并将 JSX 解析/转换为React.createElement
  • 感谢此评论有助于了解编译器如何理解 JSX

标签: javascript reactjs react-router react-redux


【解决方案1】:

如果你给 Babel 一些 JSX,you will see that JSX is just sugar for React.createElement calls。这就是为什么我们在使用 JSX 时需要导入 React。

输入

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

输出

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

【讨论】:

  • 只是一个更新:React 17 和一些较旧的指定主要版本现在包括一个新的 JSX 转换,它不需要这个显式的 React 导入。见reactjs.org/blog/2020/09/22/…
【解决方案2】:

当您尝试在您的 javascript 文件中使用 jsx 时,您的普通编译器甚至 babel 都无法理解它。虽然普通的编译器永远不会理解它。但无论如何你想说你的编译器我在文件中为你提供了一个 jsx。

import React from 'react';

上面是指示 babel 继续的方法,现在对你来说是一件容易的事。

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

以上是 jsx 语句。因此,无论何时使用它,都需要导入 React。 同样,我们在很多地方都不需要它,因为我们没有 jsx。

【讨论】:

    猜你喜欢
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 2018-11-12
    • 2019-02-22
    • 2020-01-09
    • 2021-10-28
    相关资源
    最近更新 更多