如何在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.js
和index.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.js
和index.android.js
将始终是默认react-native init
项目中的独立入口点。 如果你想让它们通过index.js
运行相同的代码库,你应该设置它,以便index.ios.js
和index.android.js
导入index.js
并注册与index.js
定义的相同的基本组件。
例如,你可以看看在这个例子的ToDo应用程序 ( Github回购在这里 )是如何完成的。
如果将index.js
放在根文件夹中,则不会直接引用index.android.js
和index.ios.js
。 所以你需要指出你导入的确切path。 请参阅下面的代码。
index.ios.js和index.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> ); } }