如何在React Native中切换抽屉式导航器?

时间:2019-01-18 13:56:26

标签: javascript reactjs react-native

我正在使用抽屉式导航。当我单击汉堡菜单图标时,抽屉导航的抽屉不起作用,我无法切换抽屉。代码1无效,但是代码2有效,有人可以帮助我找出原因吗?

代码:

    Burger menu icon code 1:

    // Inside Header
    navigationOptions: ({ navigation }) => ({
                // headerTitle: 'Rchampz',
                headerLeft:
                <TouchableOpacity  onPress={() => {navigation.dispatch(DrawerActions.toggleDrawer())} }>
                    <MenuImage navigation={navigation}/>
                </TouchableOpacity>,

//Created component and added inside navigationOptions

    const MenuImage = ({navigation}) => {
        if(!navigation.state.isDrawerOpen){
            return <TouchableOpacity><Image source={require('../assets/images/menu.png')} style={{width: 24, height: 24, resizeMode: 'contain' ,marginLeft: 15}}/></TouchableOpacity>
        }else{
            return <MenuIcon style={{paddingLeft: 10, paddingRight: 10}} name="md-arrow-back" size={30} color="black"/>
        }
    }

    Burger menu icon code 2:

    //Inside header

    navigationOptions: ({ navigation }) => ({
                // headerTitle: 'Rchampz',
                headerLeft:
                <TouchableOpacity  onPress={() => {navigation.dispatch(DrawerActions.toggleDrawer())} }>
                    <MenuImage navigation={navigation}/>
                </TouchableOpacity>,


//Created component and added inside navigationOptions

    const MenuImage = ({navigation}) => {
        if(!navigation.state.isDrawerOpen){
            return <MenuIcon style={{paddingLeft: 10, paddingRight: 10}} name="md-menu" size={30} color="black"/>
        }else{
            return <MenuIcon style={{paddingLeft: 10, paddingRight: 10}} name="md-arrow-back" size={30} color="black"/>
        }
    }

1 个答案:

答案 0 :(得分:1)

因为在第一个菜单中设置菜单图像的方式。您将图像包装在另一个TouchableOpacity中,这意味着内部TouchableOpacity正在拾取用户触摸事件。这实际上并不是您想要的行为,因为您希望headerLeft上的TouchableOpacity成为输入的接收者。因此,只需删除“多余” TouchableOpacity

// Inside Header
navigationOptions: ({ navigation }) => ({
    headerLeft:
    <TouchableOpacity onPress={() => {navigation.dispatch(DrawerActions.toggleDrawer())} }>
        <MenuImage navigation={navigation}/>
    </TouchableOpacity>,

//Created component and added inside navigationOptions
const MenuImage = ({navigation}) => {
    if(!navigation.state.isDrawerOpen){
        // No need of Touchable here. Since you want the above Touchable to pick up the onPress event.
        return <Image source={require('../assets/images/menu.png')} style={{width: 24, height: 24, resizeMode: 'contain' ,marginLeft: 15}}/>. 
    }else{
        return <MenuIcon style={{paddingLeft: 10, paddingRight: 10}} name="md-arrow-back" size={30} color="black"/>
    }
}

第二个示例起作用的原因很简单,没有多余的Touchable处理onPress事件。