【问题标题】:WC3 Sensors in React WebReact Web 中的 WC3 传感器
【发布时间】:2020-05-10 12:51:03
【问题描述】:

我正在尝试让 W3C Sensors API 在我的 React Web 应用程序(不是 React Native)中工作,基本上我找不到任何可靠的文档来让它使用 javascript 工作,这是我到目前为止生成的代码:

  import React, { Component } from "react";

  export default class Postion extends Component {
  state = {
    message: "not supported",
  };
  componentDidMount() {
    this.test();
  }

  test(){
    if(window.Accelerometer){
        this.setState({message:"supported"})
    }
  }

  render() {
    return <div>{this.state.message}</div>;
  }
}

它在桌面浏览器上显示“支持”,而在我迄今为止尝试的所有移动浏览器上显示“不支持”,所以我的问题是:如何使用传感器 API(尤其是在移动浏览器上)从加速度计获取数据?我什至可以完成?谢谢。

【问题讨论】:

    标签: reactjs w3c w3c-geolocation


    【解决方案1】:

    我还没用过。但是MDN 上总是有很好的文档:

    let acl = new Accelerometer({frequency: 60});
    
    acl.addEventListener('reading', () => {
      console.log("Acceleration along the X-axis " + acl.x);
      console.log("Acceleration along the Y-axis " + acl.y);
      console.log("Acceleration along the Z-axis " + acl.z);
    });
    
    acl.start();
    

    现在,要在 React 上实现它,你就知道了。只需要挂上componentDidMount hook即可。

    【讨论】:

    • 您好,感谢您的评论,我已经尝试过此解决方案,但我一直收到“加速度计未定义”,因为我对钩子不太熟悉,请您给我一个工作例子?谢谢。
    • 如果有帮助请告诉我:stackoverflow.com/a/52449059/2138752
    • 另外,我不是在说 react 钩子,只是说你已经熟悉 componentDidMount 钩子。这里的钩子是简单地声明一个方法。
    • 再次感谢您的回复,但是您的回复与问题有什么关系?
    • 你问如何在反应中绑定监听器,这就是我的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多