0

我即将完成反应原生开发的第一步,并且遇到访问设备传感器的问题。在我index.android.js,我做如何将侦听器添加到react-native中的传感器?

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"})') 

我做的应用程序时出现错误消息通过加载

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

在控制台中集成传感器管理器,所以包应该实际上被识别编辑。

你对这个问题有什么了解吗?

谢谢!

回答

1

addListener方法向回调函数添加另一个上下文。你可以使用

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

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

很大的帮助,谢谢! – s4inz

相关问题