【问题标题】:`npm init react-app` leads to `'React' is not defined no-undef` when changing function component to class component将功能组件更改为类组件时,`npm init react-app` 导致 `'React' is not defined no-undef`
【发布时间】:2020-12-25 05:56:03
【问题描述】:

我使用了npm init react-app appname,它在其他文件中创建了App.js。在那个文件中有一个函数组件:

function App() {
  return (
    <SomeJSX />
  );
}

我把函数组件编辑成类组件,如下:

class App extends React.Component{
  render() {
    return (
      <TheSameJSX />
    );
  }
}

现在,当我运行 npm start 时,我得到一个错误:

Failed to compile

src/App.js
  Line 4:19:  'React' is not defined  no-undef

Search for the keywords to learn more about each error.

我想我需要在某个地方添加一些设置,这些设置将自动包含 React,而无需在每个文件的顶部显式地 import 它。我该怎么做呢?为什么这个 npm 包默认不这样做?我对 javascript(以及 html 和 css)略知一二,也读过一点 React,但我完全不知道 npm 或 webpack 是如何工作的。

提前致谢!

编辑:澄清一下,我知道如何使用 javascript 导入内容。我可以轻松地将import React from 'react'; 添加到文件中并使其工作。但是,我很难相信向每个 javascript 文件添加 import 语句是推荐的方法,而且我不明白为什么不设置此示例应用程序以避免必须这样做。我弄错了吗?我真的需要在同一个项目中一遍又一遍地手动导入相同的东西吗?我可以将一个全局变量设置为React,以便我可以在任何地方使用它吗?

【问题讨论】:

    标签: javascript node.js reactjs npm webpack


    【解决方案1】:

    在你的默认函数组件中,你没有扩展任何类,只是编写一个简单的函数

    function App() {
          return (
            <SomeJSX />
          );
        }
    

    在类组件中,您实际上是通过 React 默认导出对象提供的 React.Component 扩展类 Component,因此您必须从包中导入它

    //only use one of these 
    import * as React from "react"; 
    import {Component} from "react"; // you can directly extend without writing `React.` with this import 
    import React from "react"
    

    所以你的代码是

    import React from "react";
    
    class App extends React.Component{
      render() {
        return (
          <TheSameJSX />
        );
      }
    }
    

    上述任何导入都应该可以优先于第一个和第二个。

    【讨论】:

      猜你喜欢
      • 2021-02-18
      • 2021-12-06
      • 2017-03-20
      • 2021-03-24
      • 2022-11-30
      • 2020-06-22
      • 2020-03-10
      • 2017-06-07
      • 2019-05-29
      相关资源
      最近更新 更多