关于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 () => {
      
    };
  }, []);

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

相关推荐
不是鱼2 小时前
构建React基础及理解与Vue的区别
前端·vue.js·react.js
飞翔的渴望5 小时前
antd3升级antd5总结
前端·react.js·ant design
╰つ゛木槿8 小时前
深入了解 React:从入门到高级应用
前端·react.js·前端框架
JSON_L10 小时前
小程序 - 模拟时钟
微信·微信小程序·小程序
用户305875848912512 小时前
Connected-react-router核心思路实现
react.js
哑巴语天雨1 天前
React+Vite项目框架
前端·react.js·前端框架
初遇你时动了情1 天前
react 项目打包二级目 使用BrowserRouter 解决页面刷新404 找不到路由
前端·javascript·react.js
码农老起1 天前
掌握 React:组件化开发与性能优化的实战指南
react.js·前端框架
前端没钱1 天前
从 Vue 迈向 React:平滑过渡与关键注意点全解析
前端·vue.js·react.js
高山我梦口香糖1 天前
[react] <NavLink>自带激活属性
前端·javascript·react.js