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

感谢从现在开始的答案,

我是React Native的新手,我想创build一个跨平台的应用程序,所以我创build了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); 

我想这之后它应该工作,但我得到这个错误:

在这里输入图像说明

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

 import {AppRegistry} from 'react-native'; import App from './app/App'; AppRegistry.registerComponent('appMobile', () => App); 

(用应用程序的名称replaceappMobile

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

新的项目从现在起只有一个入口点(index.js)

你正在倒退。 index.ios.jsindex.android.js将始终是默认react-native init项目中的独立入口点。 如果你想让它们通过index.js运行相同的代码库,你应该设置它,以便index.ios.jsindex.android.js导入index.js并注册与index.js定义的相同的基本组件。

例如,你可以看看在这个例子的ToDo应用程序 ( Github回购在这里 )是如何完成的。

如果将index.js放在根文件夹中,则不会直接引用index.android.jsindex.ios.js 。 所以你需要指出你导入的确切path。 请参阅下面的代码。

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) 

index.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> ); } }