react native 原生與js通信同步函數

rn-sync-function

原文地址:https://zhangjinbo619.github.io/code/2018/11/20/rn-sync-function.html

背景

在實際項目開發過程中,需要原生與js通信同步時,可使用如下方式。

代碼

  • oc 代碼
@define API_URL @"http://localhost:3000” 
@implementation ConfigManager 
RCT_EXPORT_MODULE(); 
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getApiUrl) 
{ 
    return API_URL; 
} 
@end
  • android 代碼
@ReactMethod(isBlockingSynchronousMethod = true)
public String getApiUrl() {
    return "http://localhost:3000";
}
  • js 代碼
import { NativeModules } from 'react-native’; 
const apiUrl = NativeModules.ConfigManager.getApiUrl();

注意

同步方法不支持 js remote 方式調試,會報錯。


rn-sync-function

解決方法,調試同步函數用alert、console.warn方式,并關閉 js debug remote

參考

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容