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