"React must be in scope when using JSX"(react/react-in-jsx-scope 与 "window.React = React" 在 index.js 上)

"React must be in scope when using JSX" (react/react-in-jsx-scope with "window.React = React" on index.js)

我正在关注 O'Reilly 的“Learning React”的第 5 章“React with JSX”。

我使用 create-react-app 作为基础编写了食谱应用程序。

index.js

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

import './index.css';

import App from './App';
import Menu from './Menu';

import registerServiceWorker from './registerServiceWorker';

import data from './data/recipes';

window.React = React;

ReactDOM.render(<Menu recipes={data} />, document.getElementById('root'));

registerServiceWorker();

Menu.js

import Recipes from './Recipes';

const Menu = ({recipes}) => (
    <article>
        <header>
            <h1>Delicious Recipes</h1>
        </header>
        <div className = "recipes">
        {recipes.map((recipe, i)=>    
            <Recipes key={i} {...recipe}  />
        )}
        </div>
    </article>
);

export default Menu;

并出现以下错误:

Failed to compile ./src/Menu.js
  Line 5:   'React' must be in scope when using JSX  react/react-in-jsx-scope
  Line 6:   'React' must be in scope when using JSX  react/react-in-jsx-scope
  Line 7:   'React' must be in scope when using JSX  react/react-in-jsx-scope
  Line 9:   'React' must be in scope when using JSX  react/react-in-jsx-scope
  Line 11:  'React' must be in scope when using JSX  react/react-in-jsx-scope
    
Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.

书上说“将 window.React 设置为 React 会在浏览器中全局公开 React 库。这样可以确保对 React.createElement 的所有调用都能正常工作”。但似乎我仍然需要在每个使用 JSX 的文件上导入 React。

在您的 Menu.js 文件之上导入 React:

import React from 'react'

如果您在项目中使用此库 (React),则应始终将 React 导入到使用 JSX 的特定文件中。

这是由于 JSX 文件中需要导入“React”。 React 库也必须始终在 JSX 代码的范围内,因为 JSX 编译为一个 React。

在您的情况下 'React' 必须在 Menu.js、

中导入
import React from "react"; 

this is an error most beginner react developers made.

And also You can refer

这是没有从 'react' 属性中导入 React 模块的结果,因此您可以尝试导入模块并尝试在声明函数时使用 'export' 以便于将它们导入到其他页面使用 'import {Menu} from menu' 如下所示

import React from 'react';
import Recipes from './Recipes';

export const Menu = ({recipes}) => (
    <article>
        <header>
            <h1>Delicious Recipes</h1>
        </header>
        <div className = "recipes">
        {recipes.map((recipe, i)=>    
            <Recipes key={i} {...recipe}  />
        )}
        </div>
    </article>
);

在react的最新更新中没有必要使用 我们可以在不从 React

导入 react 的情况下编写代码
import React from 'react'

导入 React

import React from 'react'

这应该有效