2016-10-20 60 views
0

我不知道我在做什麼錯,但我有我的組件內的幾個功能。但是,我無法將其中的某個功能作爲道具傳遞,因此我收到了this.nextScene不是函數。不知道我在做什麼錯 - 獲取不是功能錯誤

下面是從我的組件片段,我已經註釋掉那裏我遇到的問題:

nextScene() { 
    this.refs.navigator.push('browse'); 
    } 

    renderNavigationView() { 
    return (
     <View style={styles.drawer}> 
     <Touchable 
      onPress={this.nextScene()}  //issue here, "this.nextScene is not a function" 
     > 
      <View style={styles.container}> 
      <Text style={styles.title}>Browse</Text> 
      </View> 
     </Touchable> 
     <Touchable> 
      <View style={styles.container}> 
      <Text style={styles.title}>Button</Text> 
      </View> 
     </Touchable> 
     </View> 
    ); 
    } 

    render() { 
    return (
     <DrawerLayoutAndroid 
     ref="drawer" 
     drawerWidth={300} 
     drawerPosition={DrawerLayoutAndroid.positions.Left} 
     renderNavigationView={this.renderNavigationView}> 
     <Navigator 
      ref="navigator" 
      configureScene={(route) => { 
      if (Platform.OS === 'android') { 
       return Navigator.SceneConfigs.FloatFromBottomAndroid; 
      } 
      } } 
      initialRoute={{}} 
      renderScene={this.renderScene} 
      /> 
     </DrawerLayoutAndroid> 
    ); 
    } 

謝謝!

+0

我想你想傳遞的參考,而不是調用 - 你也可能需要結合本或使用箭頭功能,因爲'this'並不像它的窗口 – Li357

+0

嗨正確的上下文。所以,如果我嘗試'this.nextScene.bind(this)',我得到一個'不能讀取屬性'綁定'的undefined':( – user1354934

回答

3

如果你看看你呈現組件,並在renderNavigationView道具:

renderNavigationView={this.renderNavigationView} 

這似乎很好,但由於在功能this上下文window默認情況下,thiswindowrenderNavigationView。考慮你的onPress事件處理程序:

onPress={this.nextScene()} 

由於您使用this.nextScene()thiswindow的功能,你有效地試圖做window.nextScene不存在,從而引發錯誤。 (還要注意,這是一個調用 - 不是引用,刪除括號)。


所以,如果我嘗試this.nextScene.bind(this),我得到一個cannot read property 'bind' of undefined

這是因爲該功能是不確定的,因爲window.nextScene不存在。爲了解決這個問題,使用Function.prototype.bindthis正確綁定在renderNavigationViewnextScene

renderNavigationView={this.renderNavigationView.bind(this)} 

bind確實在這種情況下設置的內容在功能this上下文。由於this這裏指的是該類,該類將用於執行應該正常工作的nextScene方法。你也必須使用綁定在nextScene因爲裏面nextScene我們要this來引用,不window

onPress={this.nextScene.bind(this)} 
+0

哇!非常感謝!這個解釋真的幫助我瞭解我哪裏出錯了。 – user1354934

+0

@ user1354934沒問題,歡呼聲! –

1

利用冬天在他的回答中指出bind方法的另一種選擇是使用箭頭功能它會自動將this綁定到您的父上下文。

class MyComponent extends React.Component { 
    clickHandler = (e) => { 
    // do stuff here 
    } 

    render() { 
    return (
     <button onClick={this.clickHandler}></button> 
    ) 
    } 
} 
+0

不錯!謝謝 – user1354934

+0

Nit-pick:箭頭函數不會自動綁定this,它們甚至不會綁定它。因爲它們不綁定它,所以'this'引用封閉的上下文。 – Li357

+0

嗯......我不確定。我會看看那個。由於箭頭函數仍然是一個函數,它的工作方式似乎是內部它必須綁定到父上下文...如果它沒有綁定它將會像聲明一個普通的匿名函數一樣工作,即使你沒有明確地綁定它,仍然有它自己的上下文,一個不是父級。我要去看看這個。 –

相關問題