React组件和js库之间的Javascript通信

我一直在研究基于蓝牙的KaiOS移动应用程序,其中已经使用React.js开发了用户界面,并且我创建了一个简单的javascript类来管理基于蓝牙的操作,例如扫描,连接/断开连接,数据传输,等。我一直在尝试扫描设备时将数据或对象从Blemanager.js类发送到react组件。

以下代码已用于检查具有特定地址的设备,如果找到了该设备,请解析承诺,以便将该对象发送到React组件。现在,我确实想将扫描的设备对象发送到react组件,并检查通知的设备对象是否为必需的对象,然后停止扫描。如何使用Javascript实现。

我是iOS开发人员,对于iOS而言,我正在寻找委派或可观察的模式。

startLeScan = () => {
    return new Promise((resolve,reject) => {
      navigator.mozBluetooth.defaultAdapter.startLeScan([])
      .then(function(handlerLE) {
        handlerLE.ondevicefound = function(eventLE) {
          if (eventLE.device.address === "ed:ec:90:87:5d:86") {
            navigator.mozBluetooth.defaultAdapter.stopLeScan(eventLE.target);
            console.log('FOUND:','Address:',eventLE.device.address,'Name:',eventLE.device.name,'Type:',eventLE.device.type);

            resolve({"eventLE":eventLE})
          }
        }
      })
      .catch(function(e) {
        console.log(e);
        reject({error: e })
      });
    })
  }
fankangkangkang 回答:React组件和js库之间的Javascript通信

我会参考有关蓝牙规范的本文档,包括有关如何使用它的良好示例。

https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web

有一个characteristics对象,可以在其上附加事件处理程序。这些反过来可以激发您的类方法。

还有一个onDisconnected方法也可以触发您的方法。

,

假设您在应用程序中使用redux, 实用程序类和组件类之间的通信可以通过将存储对象向下传递到实用程序类来完成。

  1. 创建一个非组件实用程序类。
import { bindActionCreators } from 'redux';
import { setBluetoothAddresses } from './some-action-file';

class BluetoothUtility {
  constructor(store) {
    this.actions = bindActionCreators(
      { setBluetoothAddresses },store.dispatch
    )
  }

  startLeScan = () => {
     // on promise done => call this.actions.setBluetoothAddresses with resolved value
  }
}

let instance;
export const initBluetoothUtility = (store) => {
  if (!instance) {
    instance = new BluetoothUtility(store);
  }
}
  1. 在根组件中,您可以在其中使用redux提供程序
class App {
   componentDidMount() {
     initBluetoothUtility(store);
   }
}
  1. 然后在组件中,您可以使用redux存储中的值
本文链接:https://www.f2er.com/1371535.html

大家都在问