首页 > 解决方案 > 使用 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;

标签: reactjsreact-hookscomponentslowercase

解决方案


但演示组件名称应以小写字母开头

它们不是,用户定义的组件必须大写

当元素类型以小写字母开头时,它指代内置组件,如<div>or<span>并生成字符串'div'or'span'传递给React.createElement。以大写字母开头的类型,例如<Foo />编译React.createElement(Foo)并对应于您的 JavaScript 文件中定义或导入的组件。


推荐阅读