簡體   English   中英

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

[英]How to use index.js instead of (index.ios.js, index.android.js) in React Native for cross-platform app?

謝謝你們的回答,

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

我認為在此之后它應該工作,但我得到這個錯誤:

在此輸入圖像描述

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

你正在倒退這個。 index.ios.jsindex.android.js將始終是默認的react-native init項目中的單獨入口點。 如果你想擁有它們運行通過相同的代碼index.js ,你應該設定,讓index.ios.jsindex.android.js進口index.js並在規定注冊相同的基本組件index.js

例如,您可以在此示例ToDo應用程序此處為Github repo )中查看它是如何完成的。

如果將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)

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

在iOS AppDelegate.m中更改此權限

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM