[React Native]initialProps初始化app接受原生传值

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

}


链接:https://www.jianshu.com/p/16d5b48a158e
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值