【问题标题】:is there any way to use lowercase letter for a component in ReactJS?有没有办法在 ReactJS 中为组件使用小写字母?
【发布时间】:2021-09-24 14:12:04
【问题描述】:

我正在尝试制作一些组件,我是 React 的新手,我尝试了一些基础知识,例如创建存储 <h1></h1> 标签和 Hello World 的简单组件。我注意到,当我将Myfunc 的第一个字母转为小写“m”时,它只呈现空页面,尽管我也在通过something.js 更改它,我在网上搜索,似乎有无论如何,就像这里的规则一样... 有没有使用小写的组件?我经常忘记这条规则

import React from "react";
import Myfunc from "./something.js";
function App(){
    return(
       <div>
         <Myfunc/>
       </div>
    );
}
export default App;

【问题讨论】:

  • 这是否回答了您的问题stackoverflow.com/questions/33259112/…
  • @misha130 是的,但是我忘记大写很多次了,我该怎么办?
  • @JSXStarter 这个习惯会随着时间的推移而消失。最好采用大多数人遵循的标准。
  • @AvinashThakur 是的,我认为这是唯一的方法

标签: reactjs


【解决方案1】:

你可以使用小写名称的 React 组件,但你不能在 JSX 中使用它们。

如果您绝对不想将第一个字母大写,或者不想将其重新分配给大写变量 (ReactComp = reactComp),那么您可以采用这种难看的方法。

const myFunc = (props) => {
  const { name, children } = props;
  return <div>
    <h1> {name} </h1>
    <h3> a lower case component </h3>
    {children}
  </div>
}

const App = props => {
  return (
    React.createElement(
      myFunc,
      {
        name: 'My Func',
        // other props
      },
      <h6>This is a child component</h6>,
      <h6>This is another child component</h6>
    )
  )
}

ReactDOM.render(<App />, document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />

【讨论】:

  • 天哪!看起来很复杂!
  • 其实我想用大写字母但是我忘记了很多次
  • 它确实复杂而丑陋,但它是您的 JSX 代码最终将转换为的东西。我相信这会让您远离使用小写名称。
【解决方案2】:

这是文档的一部分...也许从这里您可以得到更好的主意。

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

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

【讨论】:

    猜你喜欢
    • 2019-05-15
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2021-03-11
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多