React原生JSX导出导入标识
问题描述:
我遇到一个奇怪的问题,当我export
a const
到另一个js文件。这是我的问题:React原生JSX导出导入标识
想象一下,我有两个文件index.js
和router.js
。
// in router.js
export const stackNav = StackNavigator({
Home: {
screen: Me,
navigationOptions: {
title: 'Welcome'
}
}
});
// in index.js
import { stackNav } from './router';
class MainApp extends Component {
render() {
return (
<stackNav />
);
}
}
export default MainApp;
当我用上面的代码运行,我无法运行我的应用程序,它显示红色屏幕上的错误消息:Expected a component class, got [object Object].
但是,如果我改变所有stackNav
到StackNav
,我可以运行我的应用成功。所以,我不知道为什么名称/标识符的情况很重要?
答
由于反应,和/ ReactNative组件名称必须以大写字母
答
参照官方doc开始,
用户定义组件必须大写
当一个元素类型与开始小写字母,它指的是像or这样的内置组件,并且导致传递给React.createElement的字符串'div'或'span'。
以大写字母开头的类型,例如编译为React.createElement(Foo)并对应于在JavaScript文件中定义或导入的组件。
我们推荐用大写字母命名组件。如果您确实有一个以小写字母开头的组件,请在将它用于JSX之前将其分配给大写变量。
以下是doc中的代码片段。
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" />;
}
这将会回答你的问题[https://stackoverflow.com/questions/30373343/reactjs-component-names-must-begin-with-capital-letters](https://stackoverflow.com/questions/30373343/reactjs-component-names-must-begin-with-capital-letters) –
@NeelGala您的评论对我的问题是正确的答案,我的问题与您提供的线索重复。 – bufferoverflow76