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

dav*_*dev 16 javascript android cross-platform ios react-native

谢谢你们的回答,

我是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;
Run Code Online (Sandbox Code Playgroud)

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

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

AppRegistry.registerComponent('ReactApp', () => ReactApp);
Run Code Online (Sandbox Code Playgroud)

我认为在此之后它应该工作,但我得到这个错误:

在此输入图像描述

Flo*_*s M 36

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

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

AppRegistry.registerComponent('appMobile', () => App);
Run Code Online (Sandbox Code Playgroud)

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

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

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


Mic*_*eng 7

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

例如,您可以在此示例ToDo应用程序(此处为Github repo)中查看它是如何完成的.

如果你把index.js你的根文件夹,它会产生冲突index.android.js,并index.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)
Run Code Online (Sandbox Code Playgroud)

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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)


FOL*_*LOF 5

在 iOS AppDelegate.m 中改变这个

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
Run Code Online (Sandbox Code Playgroud)

jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
Run Code Online (Sandbox Code Playgroud)