为什么AppRegistry.registerComponent(' MyApp',()=> App)工作,即使App已经是一个返回组件的函数?

时间:2018-01-27 10:02:02

标签: javascript react-native

如果我理解正确,registerComponent需要一个函数返回一个组件作为它的第二个参数,就像我在下面的第一次尝试一样。

由于App是这样一个功能,我本来希望它按原样运行,我不明白为什么我需要传递()=> App(直接传递App会导致下面的错误)

index.js:

import { AppRegistry } from 'react-native';
import {App} from './src/App';
import {Test} from './src/App';
AppRegistry.registerComponent('MyApp', () => Test); // option 1, works
AppRegistry.registerComponent('MyApp', App); // option 2, doesn't work, error below
AppRegistry.registerComponent('MyApp', () => App); // option 3, works

./ SRC / App.js:

import React, { Component } from 'react';
import {  Text,  View} from 'react-native';
export class Test extends Component<{}> {
  render() {
    return (
      <View><Text>Foo</Text></View>
    );
  }
}

export const App= () =>(
    <Test/>
);
  

ExceptionsManager.js:73检查renderApplication.js上的代码:35。

     

不变违规:元素类型无效:预期为字符串(for      内置组件)或类/函数(用于复合组件)      但得到了:对象。 ExceptionsManager.js:65

     

此错误位于:

in RCTView (at View.js:71)
in View (at AppContainer.js:102)
in RCTView (at View.js:71)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:34)

1 个答案:

答案 0 :(得分:2)

执行应用程序并返回<Test />。虽然Test是一个函数或类,但<Test />是一个对象,React.createElement的结果。这就是为什么第二个选项失败的原因。

我们需要一个返回函数/类的函数,而不是一个返回一个对象的函数。