簡體   English   中英

如何在本機中向傳感器添加偵聽器?

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

我將要進行本機開發的第一步,並且在訪問設備的傳感器時遇到問題。 在我的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() {...

...

在模擬器上運行應用程序時,確實收到錯誤消息

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

我確實通過加載將sensormanager集成到我的項目中

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

在控制台中,因此實際上應該可以識別該軟件包。

您對可能的問題有任何想法嗎?

謝謝!

addListener方法將另一個上下文添加到回調函數。 你可以用

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

要么

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