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.React为React在浏览器中全局公开 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 17中不需要导入。\n我们可以在不从React导入react的情况下编写代码
\nhttps://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
\n\n\n随着 React 17 版本的发布,我们\xe2\x80\x99想要对 JSX 转换进行一些\n改进,但我们\xe2\x80\x99并不想破坏\n现有的设置。这就是为什么我们与 Babel 合作,为想要升级的人提供新的、\n重写版本的 JSX 转换。
\n升级到新的转换是完全可选的,但它有\n一些好处:
\n\n
\n- 通过新的转换,您可以使用 JSX 而无需导入 React。
\n
React 的 eslint 默认配置仍然会发出警告。但可以禁用它:
\nhttps://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md
\n\n\n如果您使用的是 React 17 中的新 JSX 转换,则应该通过在 eslint 配置中扩展 React/jsx-runtime 来禁用此规则(将“plugin:react/jsx-runtime”添加到“extends”)。
\n
| 归档时间: |
|
| 查看次数: |
20689 次 |
| 最近记录: |