为何navigation.closeDrawer不是函数?react-navigation v2.x问题求助
我来帮你排查这个问题~先看你代码里的关键错误:你误用了navigation.actions.closeDrawer(),这不是正确的调用方式!
问题原因分析
在你使用的react-navigation 2.x版本中:
closeDrawer是navigation对象的直接方法,可以直接通过this.props.navigation.closeDrawer()调用,完全不需要加.actions前缀。- 你提到的
actions(准确说是NavigationActions)是用来创建action对象的工具,要是想用这种方式触发关闭,得配合dispatch,比如this.props.navigation.dispatch(NavigationActions.closeDrawer()),但显然直接调用封装好的closeDrawer()更简便。
你说console.log能看到navigation下有closeDrawer方法,但实际调用时找错了路径——navigation对象里根本没有你想的actions属性,自然会报“Cannot read property 'closeDrawer' of undefined”的错误。
修正后的DrawerPanel代码
把按钮的onPress逻辑改成下面这样,就能正常关闭抽屉并跳转了:
import React, { Component } from 'react'; import { ScrollView, Text } from 'react-native'; import { View } from 'react-native-animatable'; import { List, Button } from 'react-native-elements'; class DrawerPanel extends Component { render() { console.log(this.props); return ( <ScrollView style={{ backgroundColor: '#81A3A7' }}> <Button onPress={() => { // 直接调用closeDrawer方法 this.props.navigation.closeDrawer(); this.props.navigation.navigate('MainActivity'); }} backgroundColor={'#81A3A7'} containerViewStyle={{ width: '100%', marginLeft: -61 }} title='Main page' /> <Button onPress={() => { // 这里也建议加上关闭抽屉的逻辑,提升用户体验 this.props.navigation.closeDrawer(); this.props.navigation.navigate('ThisWeek'); }} backgroundColor={'#81A3A7'} containerViewStyle={{ width: '100%', marginLeft: -46 }} title='This week' /> </ScrollView> ); } } export default DrawerPanel;
额外提示
第二个按钮点击后抽屉不会自动关闭,建议也加上closeDrawer()调用,这样用户操作完抽屉后页面会更流畅~
内容的提问来源于stack exchange,提问作者Morton
相关产品推荐
相关产品推荐

