即使我的client.js没有使用它,为什么必须导入"反应"

joy*_*joy 4 reactjs

当我没有在我的client.js中导入"React"时,我正在学习React并且在我的代码不起作用时感到困惑.理想情况下,当我在代码中不使用"React"时,我不应该强制导入"react"模块.以下是代码段.

Layout.js:

import React from "react";

export  default class Layout extends React.Component {
  constructor () {
    super();
    this.name = "Dilip";
  }
  render () {
    return (
      <h1>Welcome {this.name} in React world !!</h1>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

工作代码:

import React from "react";
import ReactDOM from "react-dom";

import  Layout from "./components/Layout"

const app = document.getElementById('app');
ReactDOM.render(<Layout/>, app);
Run Code Online (Sandbox Code Playgroud)

不工作代码:

import ReactDOM from "react-dom";

import  Layout from "./components/Layout"

const app = document.getElementById('app');
ReactDOM.render(<Layout/>, app);
Run Code Online (Sandbox Code Playgroud)

当我删除导入"React"的代码时,为什么它不起作用?我没有在任何地方使用"React"因此它应该工作.它在控制台中抛出以下错误.

Uncaught ReferenceError: React is not defined
Run Code Online (Sandbox Code Playgroud)

注意:我正在关注视频

yac*_*aka 11

@Matteo错了.虽然ReactDOM确实依赖于React它,但它在自己的代码中需要它.

您需要导入的真正原因ReactJSX片段:

<Layout/>
Run Code Online (Sandbox Code Playgroud)

只有语法糖:

React.createElement(Layout)
Run Code Online (Sandbox Code Playgroud)

因此,在JSX编译之后,实际上需要React.;)

  • 这是有道理的.由于JSX使用快捷语法,因此"React"在语法上是隐藏的,但从技术上讲它是被使用的.谢谢你的解释. (2认同)