亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

React Native JSI實現(xiàn)RN與原生通信的示例代碼

 更新時間:2021年08月23日 15:13:59   作者:RiverLi  
本文主要介紹了React Native JSI實現(xiàn)RN與原生通信的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

什么是JSI

React Native JSI (JavaScript Interface) 可以使 JavaScript 和 原生模塊 更快、更簡單的通信。它也是React Native 新的架構體系中Fabric UI層 和 Turbo 模塊的核心部分。

JSI有什么不同

JSI 移除了原生代碼和JavaScript代碼之間的橋接(bridge),同時也省去了兩端相互調用時大量的JSON序列化和反序列化操作。JSI為原生和JS交互打開了新的大門。下面是一些JSI的特點:

  1. JavaScript Interface 允許我們向JavaScript 運行時注冊方法。這些方法在js環(huán)境中可以通過 global對象獲取并調用。
  2. 我們完全可以使用C++或者在iOS里使用OC ,在Android里使用Java實現(xiàn)這些注冊方法。
  3. 原先使用bridge 的方式實現(xiàn)的原生模塊可以通過增加一層C++,快速轉化為通過JSI實現(xiàn)。
  4. 在iOS端實現(xiàn)非常簡單,因為C++和OC 可以方便的實現(xiàn)混編。
  5. 在Android中,我們需要通過JNI 做一些轉化。
  6. 這些方法可以是完全同步的,這意味著不必強制使用async。await。

在iOS中使用JSI

下面我們將一步一步的在iOS工程中使用JSI實現(xiàn)原生與JS的通信。
創(chuàng)建一個新的React Native 項目

npx react-native init jsiDemo

iOS端配置

在iOS項目目錄中創(chuàng)建C++文件,example.h、 example.cpp。
example.h

#ifndef EXAMPLE_H
#define EXAMPLE_H

namespace facebook {
 namespace jsi {
  class Runtime;
 }
}

namespace example {
 void install(facebook::jsi::Runtime &jsiRuntime);
}
#endif /* EXAMPLE_H */

example.m
#include "example.h"
#include <jsi/jsi.h>
using namespace facebook::jsi;
using namespace std;

namespace example {
 void install(Runtime &jsiRuntime) {  
    auto helloWorld = Function::createFromHostFunction(jsiRuntime,
                                                       PropNameID::forAscii(jsiRuntime,
                                                                            "helloWorld"),
                                                       0,
                                                       [](Runtime &runtime,
                                                          const Value &thisValue,
                                                          const Value *arguments,
                                                          size_t count) -> Value {
        string helloworld = "helloworld";
        return Value(runtime, String::createFromUtf8(runtime,helloworld));
    });
    
    jsiRuntime.global().setProperty(jsiRuntime, "helloWorld", move(helloWorld));
    
 }
}

在上面的代碼中,我們使用 createFromHostFunction 方法創(chuàng)建了一個方法,并通過setProperty 方法將其注冊到js運行時。
接下來,我們需要創(chuàng)建一個moudle, 在moudle中執(zhí)行install 方法。
我們創(chuàng)建OC 文件,SimpleJsi.h , SimpleJsi.mm

SimpleJsi.h

#import <React/RCTBridgeModule.h>
@interface SimpleJsi : NSObject <RCTBridgeModule>
@property (nonatomic, assign) BOOL setBridgeOnMainQueue;
@end

SimpleJsi.mm

#import "SimpleJsi.h"
#import <React/RCTBridge+Private.h>
#import <React/RCTUtils.h>
#import <jsi/jsi.h>
#import "example.h"
#import <sys/utsname.h>

using namespace facebook::jsi;
using namespace std;

@implementation SimpleJsi

@synthesize bridge = _bridge;
@synthesize methodQueue = _methodQueue;

RCT_EXPORT_MODULE()

+ (BOOL)requiresMainQueueSetup {
    
    return YES;
}

- (void)setBridge:(RCTBridge *)bridge {
    _bridge = bridge;
    _setBridgeOnMainQueue = RCTIsMainQueue();
    [self installLibrary];
}

- (void)installLibrary {
    
    RCTCxxBridge *cxxBridge = (RCTCxxBridge *)self.bridge;
    
    if (!cxxBridge.runtime) {
        
        /**
         * This is a workaround to install library
         * as soon as runtime becomes available and is
         * not recommended. If you see random crashes in iOS
         * global.xxx not found etc. use this.
         */
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC),
                       dispatch_get_main_queue(), ^{
            /**
             When refreshing the app while debugging, the setBridge
             method is called too soon. The runtime is not ready yet
             quite often. We need to install library as soon as runtime
             becomes available.
             */
            [self installLibrary];
            
        });
        return;
    }
    
    example::install(*(facebook::jsi::Runtime *)cxxBridge.runtime);
}

@end

在 setBridge 方法中,我們調用了 example的 install  方法,完成方法的注冊。

RN端配置

修改App.js

import React from 'react';
import type {Node} from 'react';
import {Text, View, Button} from 'react-native';

const App: () => Node = () => {
  const [result, setResult] = React.useState();

  const press = () => {
    setResult(global.helloWorld());
  };
  return (
    // eslint-disable-next-line react-native/no-inline-styles
    <View style={{backgroundColor: '#FFFFFF', height: '100%'}}>
      <View style={{height: '10%'}} />
      <Button onPress={press} title="按鈕" />
      <Text>{'調用helloword:' + result}</Text>
    </View>
  );
};

export default App;

點擊按鈕之后,發(fā)現(xiàn)result的值為helloworld。

結果

上面我們實現(xiàn)了js 調用原生,但沒有參數(shù),接下來我們實現(xiàn)一個單參數(shù)的調用。

js調用帶參數(shù)的原生方法

我們在example.cpp  的 install 方法中增加multiply方法的注冊,從arguments 中取出入?yún)ⅰ?br />

auto multiply = Function::createFromHostFunction(jsiRuntime,
                                                     PropNameID::forAscii(jsiRuntime,
                                                                          "multiply"),
                                                     2,
                                                     [](Runtime &runtime,
                                                        const Value &thisValue,
                                                        const Value *arguments,
                                                        size_t count) -> Value {
        int x = arguments[0].getNumber();
        int y = arguments[1].getNumber();
        return Value(x * y); 
    });

jsiRuntime.global().setProperty(jsiRuntime, "multiply", move(multiply));

然后修改App.js

import React from 'react';
import type {Node} from 'react';
import {Text, View, Button} from 'react-native';

const App: () => Node = () => {
  const [result, setResult] = React.useState();

  const press = () => {
    setResult(global.multiply(2, 2));
  };
  return (
    // eslint-disable-next-line react-native/no-inline-styles
    <View style={{backgroundColor: '#FFFFFF', height: '100%'}}>
      <View style={{height: '10%'}} />
      <Button onPress={press} title="按鈕" />
      <Text>{'2*2 = ' + result}</Text>
    </View>
  );
};

export default App;

結果

原生調用JS

原生調用js主要通過jsiRuntime.global().getPropertyAsFunction(jsiRuntime, "jsMethod").call(jsiRuntime);方法實現(xiàn)。
首先我們在js中增加一個js方法。我們修改App.js 在上面增加jsMethod 方法。

import React from 'react';
import type {Node} from 'react';
import {Text, View, Button} from 'react-native';

const App: () => Node = () => {
  const [result, setResult] = React.useState();

  global.jsMethod = () => {
    alert('hello jsMethod');
  };

  const press = () => {
    setResult(global.multiply(2, 2));
  };
  return (
    // eslint-disable-next-line react-native/no-inline-styles
    <View style={{backgroundColor: '#FFFFFF', height: '100%'}}>
      <View style={{height: '10%'}} />
      <Button onPress={press} title="按鈕" />
      <Text>{'2*2 = ' + result}</Text>
    </View>
  );
};

export default App;

在原生端,我們假設在進入應用的時候觸發(fā)調用js方法,我們修改AppDelegate中的applicationWillEnterForeground 方法。

- (void)applicationWillEnterForeground:(UIApplication *)application {
  SimpleJsi *jsi = [self.bridge moduleForName:@"SimpleJsi"];
  [jsi calljs];
}

通過moduleForName方法獲取SimpleJsi對象, 然后通過SimpleJsi中的calljs 方法。

- (void)calljs {
  RCTCxxBridge *cxxBridge = (RCTCxxBridge *)self.bridge;
  Runtime &jsiRuntime = *(facebook::jsi::Runtime *)cxxBridge.runtime;
  jsiRuntime.global().getPropertyAsFunction(jsiRuntime, "jsMethod").call(jsiRuntime);
}

結果

原生調用帶參數(shù)的JS方法

多參數(shù)調用和無參調用類似,只是在call方法后面增加了參數(shù)列表。
首先我們先在js側定義方法,修改app.js

import React from 'react';
import type {Node} from 'react';
import {Text, View, Button} from 'react-native';

const App: () => Node = () => {
  const [result, setResult] = React.useState();

  global.jsMethod = () => {
    alert('hello jsMethod');
  };

  global.jsMultiply = (x, y) => {
    alert('x * y = ' + x * y);
  };

  const press = () => {
    setResult(global.multiply(2, 2));
  };
  return (
    // eslint-disable-next-line react-native/no-inline-styles
    <View style={{backgroundColor: '#FFFFFF', height: '100%'}}>
      <View style={{height: '10%'}} />
      <Button onPress={press} title="按鈕" />
      <Text>{'2*2 = ' + result}</Text>
    </View>
  );
};

export default App;

然后我們修改原生端的調用
AppDelegate.m

- (void)applicationWillEnterForeground:(UIApplication *)application {
  SimpleJsi *jsi =  [self.bridge moduleForName:@"SimpleJsi"];
//  [jsi calljs];
  [jsi callJsMultiply:4 y:4];
}

SimpleJsi.m

- (void)callJsMultiply:(int)x y:(int) y {
  RCTCxxBridge *cxxBridge = (RCTCxxBridge *)self.bridge;
  Runtime &jsiRuntime = *(facebook::jsi::Runtime *)cxxBridge.runtime;
  jsiRuntime.global().getPropertyAsFunction(jsiRuntime, "jsMultiply").call(jsiRuntime, x, y);
}

結果

在原生端調用js的函數(shù)參數(shù)

在原生中調用js參數(shù)中的函數(shù),需要通過arguments[i].getObject(runtime).getFunction(runtime).call(runtime, value);的方式觸發(fā)。

首先我們在example.cpp 中新注冊一個方法multiplyWithCallback

auto multiplyWithCallback = Function::createFromHostFunction(jsiRuntime,
                                                                 PropNameID::forAscii(jsiRuntime,
                                                                                      "multiplyWithCallback"),
                                                                 3,
                                                                 [](Runtime &runtime,
                                                                    const Value &thisValue,
                                                                    const Value *arguments,
                                                                    size_t count) -> Value {
        int x = arguments[0].getNumber();
        int y = arguments[1].getNumber();
        //調用callback
        arguments[2].getObject(runtime).getFunction(runtime).call(runtime, x * y);
        
        return Value();
        
    });
    
    jsiRuntime.global().setProperty(jsiRuntime, "multiplyWithCallback", move(multiplyWithCallback));

在js側進行調用, 修改app.js

import React from 'react';
import type {Node} from 'react';
import {Text, View, Button} from 'react-native';

const App: () => Node = () => {
  const [result, setResult] = React.useState();

  global.jsMethod = () => {
    alert('hello jsMethod');
  };

  global.jsMultiply = (x, y) => {
    alert('x * y = ' + x * y);
  };

  const press = () => {
    // setResult(global.multiply(2, 2));
    global.multiplyWithCallback(4, 5, alertResult);
  };

  const alertResult = res => {
    alert(res);
  };

  return (
    // eslint-disable-next-line react-native/no-inline-styles
    <View style={{backgroundColor: '#FFFFFF', height: '100%'}}>
      <View style={{height: '10%'}} />
      <Button onPress={press} title="按鈕" />
      <Text>{'2*2 = ' + result}</Text>
    </View>
  );
};

export default App;

點擊按鈕之后,會調用multiplyWithCallback 將alertResult 方式傳遞給原生。

結果

總結

上面就是本文對JSI 的介紹,文中的代碼,你可以在公眾號回復 JSI 獲取GitHub 下載地址。

問題

在RN Debug的情況下,global.xx 無法找到對應的方法,個人也沒有頭緒,如果你有方法解決,請聯(lián)系我,非常感謝。

參考資料

https://blog.notesnook.com/getting-started-react-native-jsi/
reactnative.maxieewong.com/
https://github.com/react-native-community/discussions-and-proposals/issues/91
ospfranco.com/

到此這篇關于React Native JSI實現(xiàn)RN與原生通信的示例代碼的文章就介紹到這了,更多相關React Native原生通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論