react native 原生与js通信同步函数

原文地址: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 方式调试,会报错。
react native 原生与js通信同步函数

解决方法,调试同步函数用alert、console.warn方式,并关闭 js debug remote

参考

相关文章:

  • 2021-11-16
  • 2022-12-23
  • 2021-11-09
  • 2021-07-08
  • 2021-04-02
  • 2021-04-06
  • 2021-07-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2021-07-29
  • 2022-12-23
  • 2021-12-02
  • 2022-12-23
相关资源
相似解决方案