reactjs - 使用 hooks 时 React 组件名称必须以大写字母开头
问题描述
我正在尝试使用 React 构建我的网站。我了解到,以大写字母开头命名功能组件是一种很好的做法,但演示组件名称应以小写字母开头。我尝试遵循这条规则,但是当我将任何钩子导入以小写开头的展示组件时,React 会显示“编译失败”。这是消息 Line 10:26: React Hook "useContext" is called in function "newCoring" 这既不是 React 函数组件也不是自定义 React Hook 函数 react-hooks/rules-of-hooks 我知道重命名组件会有所帮助,但仍然想知道为什么在不使用 React 钩子的情况下以这种方式命名表示组件是“一种好习惯”?这是我的组件:
import React, {useContext} from 'react'
import InputComponent from '../Interface Components/InputComponent'
import SelectComponent from '../Interface Components/SelectComponent'
import AddToCart from '../Interface Components/AddToCart'
import DrawButton from '../Interface Components/DrawButton'
import Signs from '../Interface Components/Signs'
import Cog from '../Interface Components/Cog'
import InputContext from '../../context/input-context'
const newCoring = () => {
const inputContext = useContext(InputContext);
return (
<div className="first-line">
<Signs/>
<InputComponent id="width" default="500">Width:</InputComponent>
<InputComponent id="height" default="500">Height:</InputComponent>
<InputComponent id="depth" default="250">Depth:</InputComponent>
<SelectComponent id="diameter" default="152" values={inputContext.diameters}>Diameter:</SelectComponent>}
<Cog/>
<AddToCart/>
<DrawButton/>
</div>
);
}
export default newCoring;
解决方案
但演示组件名称应以小写字母开头
它们不是,用户定义的组件必须大写
当元素类型以小写字母开头时,它指代内置组件,如
<div>
or<span>
并生成字符串'div'
or'span'
传递给React.createElement
。以大写字母开头的类型,例如<Foo />
编译React.createElement(Foo)
并对应于您的 JavaScript 文件中定义或导入的组件。
推荐阅读
- javascript - 角度 rxjs 管道从数组中删除元素
- gitlab - 当由 gitlab webhook 调用时,jenkins 管道中的 git 分支名称是什么
- php - 如何将多维数组转换为一维数组
- php - 选择发送到 php 时的 twitter 预输入
- pyspark - 将 DF 列转换为列表时出现 PySpark 错误
- neo4j - Neo4j:查找连接到多个类型 2 的 A 类型节点的网络
- c# - 如何将时间戳转换为日期时间?
- c++ - 区分非成员函数和头文件中的成员函数
- python - Python导入一个模块,收到系统找不到指定路径的错误
- virtualenv - ModuleNotFoundError:创建虚拟环境时没有名为“_posixsubprocess”的模块