contentComponent 中未定义的 onClick 函数 [英] Undefined function onClick in contentComponent
问题描述
我试图访问位于 createDrawerNavigator 内的 contentComponent 上的按钮内的函数.问题是传递给 contentComponent 的道具"没有我试图访问的功能,我不断收到未定义".代码如下:
Im trying to access a function inside a button on contentComponent that is inside a createDrawerNavigator. The problem is that the 'props' passed to the contentComponent does not have the function that im trying to access and i keep getting 'undefined'. Here's the code:
const MainDrawer = createDrawerNavigator(
{
Home: {
screen: HomeScreen,
},
}, {
contentComponent: (props) => (
<View style={{ flex: 1 }}>
<SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
<DrawerItems {...props} />
<Button
color='red'
title='Logout'
onPress={() => { props.logoutCurrentUser() }}
/>
</SafeAreaView>
</View>
),
})
const RootNavigator = createStackNavigator({
MainDrawer: { screen: MainDrawer},
})
class AppNavigation extends Component {
constructor(props) {
super(props);
}
logoutCurrentUser = () => {
console.log("LOGOUT PRESSED")
}
render() {
return <RootNavigator logoutCurrentUser={this.logoutCurrentUser}/>
}
}
onPress={() => { props.logoutCurrentUser() }} 是我得到错误的地方.如何正确调用这个函数?
The onPress={() => { props.logoutCurrentUser() }} is where I get the error. How to properly call this function?
提前致谢.
推荐答案
所以我设法解决了一个问题,我添加了一个 mapDispatchToProps 和单击按钮时我想调用的函数:
So I managed a workaround, I added a mapDispatchToProps with the function that I want to call when clicking the button:
const mapDispatchToProps = (dispatch) => {
return {
dispatch,
logoutCurrentUser: () => {
console.log("LOGOUT PRESSED")
}
}
}
然后在我的类 AppNavigation 上,我这样做了:
Then on my class AppNavigation i did this:
render() {
return <RootNavigator screenProps={this.props} />
}
我的MainDrawer我改成了这个
const MainDrawer = createDrawerNavigator(
{
Home: { screen: HomeScreen },
}, {
contentComponent: (props) => (
<View style={{ flex: 1 }}>
<SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
<DrawerItems {...props} />
<Button
color='red'
title='Logout'
onPress={() => { props.screenProps.logoutCurrentUser() }}
/>
</SafeAreaView>
</View>
),
})
把答案留在这里以防其他人也有同样的问题.
Leaving the answer here in case someone else also have the same problem.
这篇关于contentComponent 中未定义的 onClick 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!