[英]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.