如何在跨平台应用程序的 React Native 中使用 index.js 而不是 (index.ios.js, index.android.js)?

新手上路,请多包涵

感谢您从现在开始的答案,

我是 React Native 的新手,我想制作一个跨平台的应用程序,所以我创建了 index.js:

 import React from 'react';
import {
    Component,
    View,
    Text,
} from 'react-native';

class ReactApp extends Component {

    render() {
        return (
            <View><Text>Hello world</Text></View>
        );
    }
}

module.exports = ReactApp;

然后我从 index.ios.js 和 index.android.js 中导入了 index.js,如下所示:

 import { AppRegistry } from 'react-native';
import ReactApp from './index';

AppRegistry.registerComponent('ReactApp', () => ReactApp);

我认为在此之后它应该可以工作,但我收到此错误:

在此处输入图像描述

原文由 davut dev 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 456
2 个回答

在 React v0.49 之后,您不需要 index.ios.jsindex.android.js 。您只需要 index.js

 import {AppRegistry} from 'react-native';
import App from './app/App';

AppRegistry.registerComponent('appMobile', () => App);

(将 appMobile 替换为您的应用名称)

资料来源:( https://github.com/facebook/react-native/releases/tag/v0.49.0

从现在开始,新项目只有一个入口点 (index.js)

原文由 Floris M 发布,翻译遵循 CC BY-SA 3.0 许可协议

你正在倒退。 index.ios.jsindex.android.js 将始终是默认 react-native init 项目中的单独入口点。 If you want to have them run the same codebase via index.js , you should set it up so index.ios.js and index.android.js import index.js and registers与 index.js 中定义的基本组件相同。

例如,您可以在这个 示例 ToDo 应用程序此处为 Github 存储库)中查看它是如何完成的。

如果将 index.js 放在根文件夹中,当您不直接引用它时,它将与 index.android.jsindex.ios.js 冲突。因此,您需要在导入中指出确切的路径。请参阅下面的代码。

index.ios.jsindex.android.js (相同内容)

 import React from 'react';
import { AppRegistry } from 'react-native'
import ReactApp from './index.js'
// Had you placed index.js in another folder like `./app`, you could instead do your import with this shorthand:
// import ReactApp from './app'

AppRegistry.registerComponent('ReactApp', () => ReactApp)

索引.js

 // Note: I noticed that you imported Component from the wrong place. That might also be contributing to your issue so I fixed it here.
import React, { Component } from 'react';
import {
    View,
    Text,
} from 'react-native';

// Unless you are exporting multiple things from a single file, you should just use this.
// It's more idiomatic than using module.exports = ReactApp;
export default class ReactApp extends Component {
    render() {
        return (
            <View><Text>Hello world</Text></View>
        );
    }
}

原文由 Michael Cheng 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题