美文网首页iOS开发
[React Native]initialProps初始化app

[React Native]initialProps初始化app

作者: fencex | 来源:发表于2017-06-16 11:08 被阅读1105次

    需求


    从androidManifest.xml 或者 ios Info.plist 定义变量,根据变量对 app 作相应处理

    寻找方案


    打开app远程调试 Debug JS remotely 的时候,可以在浏览器中看到 Running application *** with appParams:{"rootTag":1, "initialProps":{}}..如下图:

    调试截图

    看到 initialProps 我们能猜想到,初始化app的时候,肯定有方法可以从原生传值给React Native

    解决方案


    android 部分

    MainActivity.java

    package com.helloworld;
    
    import android.content.Context;
    import android.content.pm.ApplicationInfo;
    import android.content.pm.PackageManager;
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    
    import com.facebook.react.ReactActivity;
    import com.facebook.react.ReactActivityDelegate;
    
    
    public class MainActivity extends ReactActivity {
    
        /**
         * Returns the name of the main component registered from JavaScript.
         * This is used to schedule rendering of the component.
         */
        @Override
        protected String getMainComponentName() {
            return "Hello React Native";
        }
    
        @Override
        protected void onResume() {
            super.onResume();
        }
    
        @Override
        protected void onPause() {
            super.onPause();
        }
    
         /**
         * 新增方法 传launch options
         */
        @Override
        protected ReactActivityDelegate createReactActivityDelegate() {
            return new ReactActivityDelegate(this, getMainComponentName()) {
                @Nullable
                @Override
                protected Bundle getLaunchOptions() {
                    Bundle initialProps = new Bundle();
    
                    Context context = MainApplication.applicationContext;
                    String channelName = "auto";
                    String appType = "app";
                    try {
                        PackageManager packageManager = context.getPackageManager();
                        if (packageManager != null) {
                            // 注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中,而不是某activity标签中,所以用ApplicationInfo
                            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                            if (applicationInfo != null) {
                                if (applicationInfo.metaData != null) {
                                    channelName = applicationInfo.metaData.getString("UMENG_CHANNEL");
                                    appType = applicationInfo.metaData.getString("APP_TYPE");
                                }
                            }
                        }
                    } catch (PackageManager.NameNotFoundException e) {
                        channelName = "auto";
                        appType = "app";
                    }
    
                    initialProps.putString("appChannel", channelName);
                    initialProps.putString("appType", appType);
                    return initialProps;
                }
            };
        }
    }
    

    iOS 部分

    从 Info.plist 获取所需键值对,传值给React Native

    AppDelegate.m

    // 这里 初始化某些 appType 和 appChannel
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:bundlePath];
    NSString *appType = [dict objectForKey:@"AppType"];
    NSString *appChannel = [dict objectForKey:@"AppChannel"];
    
    // 这里
    NSDictionary *initialProps = [NSDictionary dictionaryWithObjectsAndKeys:appType, @"appType", appChannel, @"appChannel", nil];
    
    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                     moduleName:@"HelloReactNative"
                                     initialProperties:initialProps  // 还有这里
                                     launchOptions:launchOptions];
    rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    UIViewController *rootViewController = [UIViewController new];
    rootViewController.view = rootView;
    self.window.rootViewController = rootViewController;
    [self.window makeKeyAndVisible];
    return YES;
    

    React Native 部分

    调试截图

    如上图,调试发现已经把值传过来啦,

    index.ios.js
    index.android.js

    import React, {Component} from 'react';
    import {
      AppRegistry
    } from 'react-native';
    import HelloReactNative from './App/View/HelloReactNative';
    
    AppRegistry.registerComponent('HelloReactNative', () => HelloReactNative);
    

    HelloReactNative.js

    import React, {Component} from "react";
    import {View,Text} from "react-native";
    
    export default class HelloReactNative extends Component {
      constructor(props) {
        super(props);
        this.lastBackPressed = 0;
    
        // 从 initialProps 读取
        this.appType = props.hasOwnProperty('appType') ? props.appType : 'app';
        this.appChannel = props.hasOwnProperty('appChannel') ? props.appChannel : 'auto';
      }
      
      render() {
        return (
          <View>
            <Text>Hello React Native {this.appType} {this.appChannel}</Text>
          </View>
        );
      }
    
    }
    

    哦了

    欢迎留言交流 : D

    相关文章

      网友评论

        本文标题:[React Native]initialProps初始化app

        本文链接:https://www.haomeiwen.com/subject/qrxotxtx.html