“使用 JSX 时 React 必须在范围内”(react/react-in-jsx-scope 与 index.js 上的“window.React = React”)

ohk*_*s11 14 jsx reactjs react-dom create-react-app

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

我编写了 Recipes Appcreate-react-app作为基础。

索引.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();
Run Code Online (Sandbox Code Playgroud)

菜单.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;
Run Code Online (Sandbox Code Playgroud)

并有以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

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

Edu*_*ard 25

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

import React from 'react'
Run Code Online (Sandbox Code Playgroud)

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

  • 但我确实在 React 18.0.0 中看到了这个错误 (7认同)
  • 我使用react18.2.0,但仍然出现此错误。我以为这是因为我使用了 eslint 并且添加了规则 {"react/jsx-uses-react": "off", "react/react-in-jsx-scope": "off",} 但它仍然如此不工作@ShanmukhaSampathKumar (3认同)

vib*_*bhu 7

在react 17中不需要导入。\n我们可以在不从React导入react的情况下编写代码

\n

https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html

\n
\n

随着 React 17 版本的发布,我们\xe2\x80\x99想要对 JSX 转换进行一些\n改进,但我们\xe2\x80\x99并不想破坏\n现有的设置。这就是为什么我们与 Babel 合作,为想要升级的人提供新的、\n重写版本的 JSX 转换。

\n

升级到新的转换是完全可选的,但它有\n一些好处:

\n
    \n
  • 通过新的转换,您可以使用 JSX 而无需导入 React。
  • \n
\n
\n

React 的 eslint 默认配置仍然会发出警告。但可以禁用它:

\n

https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md

\n
\n

如果您使用的是 React 17 中的新 JSX 转换,则应该通过在 eslint 配置中扩展 React/jsx-runtime 来禁用此规则(将“plugin:react/jsx-runtime”添加到“extends”)。

\n
\n