简体   繁体   中英

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

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

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. 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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