[英]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
指的是window
中renderNavigationView
。 考慮您的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
正確雙方 renderNavigationView
和nextScene
:
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.