我正在使用JSBin上的ReactJS框架.
我注意到如果我的组件名称以小写字母开头,则它不起作用.
例如,以下内容不呈现:
var fml = React.createClass({
  render: function () {
    return <a href='google.com'>Go</a>
  }
});
React.render(<fml />, document.body);
但只要我更换fml用Fml它渲染.
有没有理由我不能用小写字母开始标记?
Ale*_*erg 178
在JSX中,小写标记名称被认为是HTML标记.但是,带点(属性访问器)的小写标签名称不是.
请参阅HTML标记与React组件.
<component />编译成React.createElement('component')(html标签)<Component /> 编译成 React.createElement(Component)<obj.component /> 编译成 React.createElement(obj.component)And*_*ahl 42
Morphaus给出了一个非常好的答案,只想添加另一个细节.React用于包含诸如divetc之类的众所周知的元素名称的白名单,用于区分DOM元素和React组件.
但是因为维护该列表并不是那么有趣,并且因为Web组件可以创建自定义元素,所以它们规定所有React组件必须以大写字母开头,或者包含一个点.
用户定义的组件必须大写
当元素类型以小写字母开头时,它引用内置组件(如<div>or)<span>,并生成字符串 ' div' 或'span'传递给React.createElement。以大写字母开头的类型,例如<Foo />编译到React.createElement(Foo)并对应于 JavaScript 文件中定义或导入的组件。
React 建议使用大写字母命名组件。如果您确实有一个以小写字母开头的组件,请先将其分配给大写变量,然后再在JSX.
例如,此代码将不会按预期运行:
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" />;
}
为了解决这个问题,我们将 hello 重命名为 Hello 并
<Hello />在引用它时使用:
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" />;
}
这是参考
当元素类型以小写字母开头时,它指的是诸如或的内置组件,并导致将字符串'div'或'span'传递给React.createElement。以大写字母开头的类型,例如编译为React.createElement(Foo)并对应于在JavaScript文件中定义或导入的组件。
另请注意:
我们建议使用大写字母命名组件。如果确实有一个以小写字母开头的组件,请在JSX中使用它之前将其分配给大写变量。
这意味着必须使用:
const Foo = foo;在foo用作JSX中的Component元素之前。
JSX标签的第一部分决定了 React 元素的类型,基本上有一些约定大写、小写、点符号。
大写和点符号类型表示JSX标记指的是 React 组件,因此如果您使用 JSX <Foo />compile to React.createElement(Foo) 
OR 
 <foo.bar />compile toReact.createElement(foo.bar)并对应于在您的 JavaScript 文件中定义或导入的组件。
而小写类型指示内置组件,如<div>或<span>并导致字符串'div'或'span'传递给React.createElement('div')。
React 建议使用大写字母命名组件。如果您确实有一个以小写字母开头的组件,请在将其用于JSX.
| 归档时间: | 
 | 
| 查看次数: | 27548 次 | 
| 最近记录: |