如何在React Native中使用index.js代替(index.ios.js,index.android.js)进行跨平台应用?

时间:2017-06-28 13:19:02

标签: javascript android ios react-native cross-platform

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

我是 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);

我认为在此之后它应该有效,但我明白了 错误:

enter image description here

3 个答案:

答案 0 :(得分:34)

在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)

答案 1 :(得分:7)

你正在倒退这件事。 index.ios.jsindex.android.js始终是默认react-native init项目中的单独入口点。如果您想让它们通过index.js运行相同的代码库,则应将其设置为index.ios.jsindex.android.js import index.js并注册index.js中定义的相同基本组件{1}}。

例如,您可以在example ToDo appGithub repo here)中查看它是如何完成的。

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

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

答案 2 :(得分:3)

在iOS AppDelegate.m中更改此

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];