你真的需要在创建钩子时导入 'React' 吗? (反应钩子)

Do you really need to import 'React' when creating hooks? (React-hooks)

我看到了 https://reactjs.org/docs/hooks-custom.html 他们总是这样做的例子:

import React, { useState, useEffect } from 'react';

但是 React 并没有真正在文件中使用,我们真的需要它吗?为什么?

我问这个问题是因为我遇到了 eslint 的问题:

'React' is defined but never used no-unused-vars - 我正在使用 create-react-app 3.0.1,其中已经包含了 eslint -(我不确定如何解决这个问题 - 已经尝试过 和也尝试将其添加到 package.json eslintConfig 但仍然没有)

如果要渲染 JSX,则需要 React

为避免 eslint 警告,您应该使用 react-in-jsx-scope rule from eslint-plugin-react.

在那条规则中,它也解释了为什么你需要在文件中使用 React,即使你不使用它(你认为你不使用它,但如果你渲染 JSX,你做)。

When using JSX, <a /> expands to React.createElement("a"). Therefore the React variable must be in scope. If you are using the @jsx pragma this rule will check the designated variable and not the React one.

来自 React 官方文档:

Fundamentally, JSX just provides syntactic sugar for the React.createElement(component, props, ...children) function. The JSX code:

<MyButton color="blue" shadowSize={2}>Click Me</MyButton>

compiles into:

React.createElement(MyButton, {color: 'blue', shadowSize: 2},'Click Me' )

You can also use the self-closing form of the tag if there are no children. So:

<div className="sidebar" /> 

compiles into:

React.createElement('div', {className: 'sidebar'}, null )

https://reactjs.org/docs/jsx-in-depth.html

EDIT Hooks 也在 React 命名空间下,React.useState ...etc

React 17 有一个新的 JSX 转换,不再需要导入(也向后移植到新版本 16.14.0、15.7.0 和 0.14.10)。你可以在这里读更多关于它的内容: https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html

// no import needed
const App = () => <div>hello!</div>

但是,您仍然需要导入才能使用钩子:

import { useState } from 'react'

const App = () => {
  const [stuff, setStuff] = useState('stuff')

  return <div>{stuff}</div>
}

文档还 link 一个脚本来自动更新项目中的所有文件以修复所有导入。就个人而言,我习惯于只使用 React.useWhatever 形式,所以我从来不需要弄乱 import 语句,但使用命名导入可能会减少最终包的大小。

文档说命名导入现在是推荐的方式,所以不推荐这样做,但如果你真的想保留 React 导入,你可以设置下面的 eslint 规则来阻止它抱怨.请注意,这将继续在所有文件中要求它。

"react/jsx-uses-react": "error"