ReactJS 组件名称必须以大写字母开头?

ReactJS component names must begin with capital letters?

我正在 JSBin 上玩 ReactJS 框架。

我注意到,如果我的组件名称以小写字母开头,它将不起作用。

例如以下内容不会呈现:

var fml = React.createClass({
  render: function () {
    return <a href='google.com'>Go</a>
  }
});

React.render(<fml />, document.body);

但是,一旦我将 fml 替换为 Fml,它就会渲染。

为什么我不能以小写字母开头标签?

在 JSX 中,小写的标签名称被认为是 HTML 标签。但是,带点的小写标签名称(属性 访问器)不是。

参见HTML tags vs React Components

  • <component /> 编译为 React.createElement('component')(html 标签)
  • <Component /> 编译为 React.createElement(Component)
  • <obj.component /> 编译为 React.createElement(obj.component)

@Alexandre Kirszenberg 给出了很好的答案,只是想添加另一个细节。

React 曾经包含一个众所周知的元素名称白名单,例如 div 等,用于区分 DOM 元素和 React 组件。

但是由于维护该列表并不是那么有趣,并且由于 Web 组件可以创建自定义元素,因此他们制定了 所有 React 组件必须以大写字母开头的规则, 或者包含一个点.

在 JSX 中,React 类 被大写以使 XML 兼容,因此它不会被误认为是 HTML 标签。如果 react 类 没有大写,它是一个 HTML 标签作为预定义的 JSX 语法。

JSX标签的第一部分决定了React元素的类型,基本上有一些约定大写,小写,点符号.

大写和点符号类型表示JSX标签指的是一个React组件, 因此,如果您使用 JSX <Foo /> 编译为 React.createElement(Foo)

<foo.bar /> 编译为 React.createElement(foo.bar) 并对应于定义或导入的组件你的 JavaScript 文件。

虽然 小写类型 指示内置组件,如 <div><span> 并导致字符串 'div''span' 传递给 React.createElement('div').

React 推荐使用大写字母命名组件。如果您确实有一个以小写字母开头的组件, 在 JSX.

中使用之前将其分配给大写变量

来自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.

另请注意:

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.

这意味着必须使用:

const Foo = foo; 在使用 foo 作为 JSX 中的组件元素之前。

User define components must be Capitalized

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

React 推荐使用大写字母命名组件。如果您确实有一个以小写字母开头的组件,请在 JSX.

中使用它之前将其分配给大写变量

For example, this code will not run as expected:

import React from 'react';

// Wrong! This is a component and should have been capitalized:
function hello(props) {
  // Correct! This use of <div> is legitimate because div is a valid HTML tag:
  return <div>Hello {props.toWhat}</div>;
}

function HelloWorld() {
  // Wrong! React thinks <hello /> is an HTML tag because it's not capitalized:
  return <hello toWhat="World" />;
}

To fix this, we will rename hello to Hello and use <Hello /> when referring to it:

import React from 'react';

// Correct! This is a component and should be capitalized:
function Hello(props) {
  // Correct! This use of <div> is legitimate because div is a valid HTML tag:
  return <div>Hello {props.toWhat}</div>;
}

function HelloWorld() {
  // Correct! React knows <Hello /> is a component because it's capitalized.
  return <Hello toWhat="World" />;
}

这里是reference