关于react native项目中使用react-native-wechat-lib@3.0.4

关于react native项目中使用react-native-wechat-lib@3.0.4

插件官网

https://www.npmjs.com/package/react-native-wechat-lib/v/3.0.4

安装依赖包(Android和iOS下载插件完成后记得更新依赖,)

npm i react-native-wechat-lib@3.0.4

Android中配置

1.在项目文件夹下面创建文件夹wxapi(如上图)

wxapi/WXEntryActivity.java

package 包名.wxapi;

// react-native-wechat-lib support (
import android.app.Activity;
import android.os.Bundle;
import com.wechatlib.WeChatLibModule;

public class WXEntryActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WeChatLibModule.handleIntent(getIntent());
    finish();
  }
}
// )

2.在文件MainApplication.java中如下配置

package 包名;

import android.app.Application;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactNativeHost;
import com.facebook.soloader.SoLoader;
import java.util.List;
// react-native-wechat-lib support (
import com.wechatlib.WeChatLibPackage;
// )

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new DefaultReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          // packages.add(new MyReactNativePackage());
          // react-native-wechat-lib support (
          // Packages that cannot be autolinked yet can be added manually here, for example:
          packages.add(new WeChatLibPackage());
          // )
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }

        @Override
        protected boolean isNewArchEnabled() {
          return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
        }

        @Override
        protected Boolean isHermesEnabled() {
          return BuildConfig.IS_HERMES_ENABLED;
        }
      };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
      // If you opted-in for the New Architecture, we load the native entry point for this app.
      DefaultNewArchitectureEntryPoint.load();
    }
    ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
  }
}

3.在文件AndroidManifest.xml中添加如下配置

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!-- 相机权限 -->
    <uses-permission android:name="android.permission.CAMERA" />
    <!-- 如果需要使用麦克风进行视频录制 -->
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <!-- 如果需要使用相机胶卷 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- 地址定位 -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter android:autoVerify="true">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
              android:host="xxx"
              android:pathPrefix="/"
              android:scheme="xxxxx" />

        </intent-filter>

      </activity>
      <!--  react-native-wechat-lib support ( -->
      <activity
        android:name=".wxapi.WXEntryActivity"
        android:label="@string/app_name"
        android:exported="true"
        android:taskAffinity="包名"
        android:launchMode="singleTask"
      />
      <!-- ) -->
    </application>
    <!--  react-native-wechat-lib support ( -->
    <queries>
      <package android:name="com.tencent.mm" />
    </queries>
    <!-- ) -->
</manifest>

IOS配置

到微信下载最新sdk,放在上图位置

在Xcode进行环境配置:如图



1.在AppDelegate.h文件添加如下代码:

#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
#import "WXApi.h"

@interface AppDelegate : RCTAppDelegate<WXApiDelegate>

@end

2.在AppDelegate.mm文件添加如下代码:

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <React/RCTLinkingManager.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"项目名称";
  // You can add your custom initial props in the dictionary below.
  // They will be passed down to the ViewController used by React Native.
  self.initialProps = @{};

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}
//ali
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
  return [RCTLinkingManager application:application openURL:url
                      sourceApplication:sourceApplication annotation:annotation];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
  return [RCTLinkingManager application:application openURL:url options:options];
}
//weixin
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application
  continueUserActivity:(NSUserActivity *)userActivity
  restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable
  restorableObjects))restorationHandler {
  // 触发回调方法
  [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
  return [WXApi handleOpenUniversalLink:userActivity
  delegate:self];
}

@end

3.Info.plist文件

<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLName</key>
			<string>alipay</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>alipayxxxxx</string>
			</array>
		</dict>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLName</key>
			<string>weixin</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>wxxxxxx</string>
			</array>
		</dict>
	</array>
<key>LSApplicationQueriesSchemes</key>
	<array>
		<string>iosamap</string>
		<string>baidumap</string>
		<string>qqmap</string>
		<string>alipay</string>
		<string>weixin</string>
		<string>wechat</string>
		<string>weixinULAPI</string>
		<string>weixinURLParamsAPI</string>
	</array>

在login.jsx页面中使用

import * as WeChat from 'react-native-wechat-lib';

//微信授权登录
      WeChat.sendAuthRequest('snsapi_userinfo', 'wechat_sdk_demo')
        .then(response => {
          console.warn(response); // 处理授权登录后的结果
         
        })
        .catch(error => {
          console.warn(error); // 处理授权登录后的结果
        });

useEffect(() => {
    console.log('[登录]');
    WeChat.registerApp(
      'wxxxxx',
      'https://xxxxx.com/',
    );
    return () => {
      
    };
  }, []);

备注:文档官方文档更加详细

相关推荐
阿伟来咯~1 小时前
记录学习react的一些内容
javascript·学习·react.js
吕彬-前端1 小时前
使用vite+react+ts+Ant Design开发后台管理项目(五)
前端·javascript·react.js
学前端的小朱1 小时前
Redux的简介及其在React中的应用
前端·javascript·react.js·redux·store
Rainbow_Technology2 小时前
劫持微信聊天记录并分析还原 —— 数据库结构讲解(四)
微信·微信聊天记录查看·微信聊天记录破解
bysking2 小时前
【前端-组件】定义行分组的表格表单实现-bysking
前端·react.js
September_ning7 小时前
React.lazy() 懒加载
前端·react.js·前端框架
web行路人7 小时前
React中类组件和函数组件的理解和区别
前端·javascript·react.js·前端框架
番茄小酱0017 小时前
Expo|ReactNative 中实现扫描二维码功能
javascript·react native·react.js
Rattenking9 小时前
React 源码学习01 ---- React.Children.map 的实现与应用
javascript·学习·react.js
熊的猫10 小时前
JS 中的类型 & 类型判断 & 类型转换
前端·javascript·vue.js·chrome·react.js·前端框架·node.js