2016-09-25 13 views
2

我有一個組件要捕獲使用panResponder的手勢事件,但是當試圖遠程調試(在chome中)時,'this'上下文引用了DedicatedWorkerGlobalScope的一個實例而不是類實例。React native'this'引用dedicatedWorkerGlobalScope而不是類實例

說我有一個簡單的組件

import React, { Component } from 'react'; 

import { 
    View, 
    Text 
    PanResponder 
} from 'react-native'; 


class MyC extends Component 
{ 
    constructor(props) 
    { 
     super(props); 
     this.panResponder = PanResponder.create({ 

      onStartShouldSetPanResponder :() => true, 
      onMoveShouldSetPanResponder :() => true, 
      onPanResponderGrant : this.panResponderGranted , 
     }) 
    } 

    panResponderGranted = (e, gestureState) => { 

     this.setState({offset : gestureState.dx}); //this.setState is undefined 
    } 

    render(){ 

     return (<View />) 
    } 

} 

現在每當我經過panResponderGranted功能一步,我看的第一級封閉,我可以看到,有一個變量命名_this具有正確引用類的實例。我調試錯了?這是預期的行爲,還是一個錯誤?

回答

2

您需要綁定panResponderGranted,因爲ES6不會自動綁定函數。

I.e.

onPanResponderGrant : this.panResponderGranted.bind(this), 
+0

但仔細看看函數表達式,我正在分配而不是聲明函數,而且這是一個箭頭函數,我的理解是,它正確地將其上下文綁定到實例。 –

+0

其實,不,我只是試了一下,這解決了我的問題..但我覺得它很奇怪,它從來沒有拋出任何未定義的錯誤整個時間。該函數將執行,但調試器不會提取值。我將'.bind(this)'附加到'.create'方法,現在我可以在調試器上看到這些值。也只是爲了捍衛我的第一條評論,我將我的代碼基於[react-native-drawer](https://github.com/root-two/react-native-drawer/blob/master/index.js#L187)它具有分配給屬性的功能,並且正確地綁定「this」上下文.... –

相關問題