簡體   English   中英

不知道我在做什么錯-獲取不是函數錯誤

[英]Not sure what I am doing wrong - getting is not a function errors

我不確定自己在做什么錯,但是我的組件中有一些功能。 但是,我無法將這些功能之一作為道具傳遞,我收到了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>
    );
  }

謝謝!

如果您查看正在渲染的組件和renderNavigationView

renderNavigationView={this.renderNavigationView}

這似乎很好,但由於this方面的功能是window在默認情況下, this指的是windowrenderNavigationView 考慮您的onPress事件處理程序:

onPress={this.nextScene()}

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


因此,如果我嘗試this.nextScene.bind(this)this.nextScene.bind(this)得到cannot read property 'bind' of undefined

這是因為該函數未定義,因為window.nextScene不存在。 為了解決這個問題,使用Function.prototype.bind綁定的this正確雙方 renderNavigationViewnextScene

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

在這種情況下, bind作用是在函數中設置this上下文。 由於this這里指的是類,類將被用於執行nextScene方法,它應該正常工作。 您還必須在nextScene上使用bind,因為在nextScene內部,我們希望this引用 ,而不是window

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

溫特在回答中指出的使用bind方法的另一種替代方法是使用箭頭函數, this函數會自動將其綁定到父上下文。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM