简体   繁体   English

如何在本机中向传感器添加侦听器?

[英]How to add a listener to a sensor in react-native?

I'm about to do my first steps in react-native development and I'm having problems with accessing the device's sensors. 我将要进行本机开发的第一步,并且在访问设备的传感器时遇到问题。 In my index.android.js, I'm doing 在我的index.android.js中,我正在做

import {
  DeviceEventEmitter
} from 'react-native';

import { SensorManager } from 'NativeModules';
var mSensorManager = require('NativeModules').SensorManager;

export default class PropertyFinder extends Component {

  constructor(props) {
     super(props);

     this.state = {
       titleText: "Bird's Nest"
     };

     mSensorManager.startAccelerometer(100);

     DeviceEventEmitter.addListener('Accelerometer', function (data) {
       this.setState({ titleText: "ttt" })
     });
   }

  render() {...

... ...

I do get an error message when running the app on an emulator which is 在模拟器上运行应用程序时,确实收到错误消息

undefined is not a function (evaluating 'this.setState({titleText:"ttt"})')

I did integrate the sensormanager in my project by loading 我确实通过加载将sensormanager集成到我的项目中

npm i react-native-sensor-manager --save

in the console, so the package should actually be recognized. 在控制台中,因此实际上应该可以识别该软件包。

Do you have any idea of what the issue could be? 您对可能的问题有任何想法吗?

Thanks! 谢谢!

The addListener method adds another context to the callback function. addListener方法将另一个上下文添加到回调函数。 You could use 你可以用

var that = this;
DeviceEventEmitter.addListener('Accelerometer', function (data) {
  that.setState({ titleText: "ttt" })
});

or 要么

DeviceEventEmitter.addListener('Accelerometer', function (data) {
  this.setState({ titleText: "ttt" })
}.bind(this));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM