ReactJS component names must begin with capital letters?

后端 未结 5 1974
忘了有多久
忘了有多久 2020-11-22 04:56

I am playing around with the ReactJS framework on JSBin.

I have noticed that if my component name starts with a lowercase letter it does not work.

For instan

相关标签:
5条回答
  • 2020-11-22 05:18

    From the official React reference:

    When an element type starts with a lowercase letter, it refers to a built-in component like or and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.

    Also note that:

    We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.

    Which means one has to use:

    const Foo = foo; before using foo as a Component element in JSX.

    0 讨论(0)
  • 2020-11-22 05:20

    @Alexandre Kirszenberg gave a very good answer, just wanted to add another detail.

    React used to contain a whitelist of well-known element names like div etc, which it used to differentiate between DOM elements and React components.

    But because maintaining that list isn't all that fun, and because web components makes it possible to create custom elements, they made it a rule that all React components must start with a upper case letter, or contain a dot.

    0 讨论(0)
  • 2020-11-22 05:23

    The first part of a JSX tag determines the type of the React element, basically there is some convention Capitalized, lowercase, dot-notation.

    Capitalized and dot-notation types indicate that the JSX tag is referring to a React component, so if you use the JSX <Foo /> compile to React.createElement(Foo)
    OR
    <foo.bar /> compile to React.createElement(foo.bar) and correspond to a component defined or imported in your JavaScript file.

    While the lowercase type indicate to a built-in component like <div> or <span> and results in a string 'div' or 'span' passed to React.createElement('div').

    React recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.

    0 讨论(0)
  • 2020-11-22 05:33

    In JSX, lower-case tag names are considered to be HTML tags. However, lower-case tag names with a dot (property accessor) aren't.

    See HTML tags vs React Components.

    • <component /> compiles to React.createElement('component') (html tag)
    • <Component /> compiles to React.createElement(Component)
    • <obj.component /> compiles to React.createElement(obj.component)
    0 讨论(0)
  • 2020-11-22 05:37

    In JSX, React Classes are capitalized to make XML compatible, so that it is not mistaken for an HTML tag. If the react classes are not capitalized, it is an HTML tag as pre-defined JSX syntax.

    0 讨论(0)
提交回复
热议问题