Why do I need to import React from 'react' in the index.js file when it's not neccessary to import react anymore?

huangapple go评论52阅读模式
英文:

Why do I need to import React from 'react' in the index.js file when it's not neccessary to import react anymore?

问题

> 我正在学习React.js。我看到在版本17之后不再需要导入React了。我的当前React版本是v18.2.0。我正在使用这段代码:

// import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

> 我遇到了这个错误:

编译失败。

[eslint]
src\index.js
第8行第4列:'React' 未定义 react/jsx-no-undef

搜索关键词以了解每个错误的详细信息。
[eslint] 中的错误
src\index.js

第8行第4列:'React' 未定义 react/jsx-no-undef

搜索关键词以了解每个错误的详细信息。

webpack编译时出现1个错误

我需要导入React吗?我该如何避免这个错误?

我已经注释掉了 import React from 'react'; 这行代码,但仍然遇到了上述错误。

英文:

> I am learning React.js. I saw that after version 17 it's no longer needed to import React anymore. My currrent react version is v18.2.0. I am using this code:

// import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom/client&#39;;
import &#39;./index.css&#39;;
import App from &#39;./App&#39;;

const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));
root.render(
  &lt;React.StrictMode&gt;
    &lt;App /&gt;
  &lt;/React.StrictMode&gt;
);

> I am getting this error:

Failed to compile.

[eslint]
src\index.js
Line 8:4: 'React' is not defined react/jsx-no-undef

Search for the keywords to learn more about each error.
ERROR in [eslint]
src\index.js

Line 8:4: 'React' is not defined react/jsx-no-undef

Search for the keywords to learn more about each error.

webpack compiled with 1 error

Do I have to import React from 'react'? What can I do to avoid this error?

I have commented out the import React from &#39;react&#39;; line and I am getting the error mention above.

I expect my code to compile successfully..

答案1

得分: 1

这个错误是由于 eslint 而不是 React 导致的,在 React 17 中,JSX 转换发生了变化。

在你的 eslint 配置文件中,请关闭这些选项:

"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off"

这样应该可以解决这个错误。

英文:

Simply this error comes from eslint not react as of react 17, jsx transformation has changed.

In you eslint config file, place turn these off:

&quot;react/jsx-uses-react&quot;: &quot;off&quot;,
&quot;react/react-in-jsx-scope&quot;: &quot;off&quot;

This should clear the error

huangapple
  • 本文由 发表于 2023年5月14日 14:22:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76246113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定