Реагируйте с навигацией - pop () идет назад к корню, а не к предыдущей странице - PullRequest
0 голосов
/ 01 апреля 2019

Я пытаюсь добавить кнопки назад в компонент Sidemenu на заказ.

Вот моя настройка navigation.js:

import { createAppContainer, createStackNavigator, createDrawerNavigator } from 'react-navigation';
import App from '../components/App';
import HomeView from '../components/HomeView';
import CheckIn from '../components/CheckIn';
import LoginView from '../components/LoginView';
import LrmDocs from '../components/LrmDocs';
import Rota from '../components/Rota';
import SideMenu from '../components/util/SideMenu';



const InitStack = createStackNavigator({
  AppContainer: App,
  LoginViewContainer:LoginView,
});


const RootStack = createDrawerNavigator({
  Auth:InitStack,

  HomeViewContainer: HomeView,
  RotaContainer: Rota,
  CheckInContainer:CheckIn,
  LrmDocsContainer: LrmDocs,
},
{
  drawerPosition: 'right',
  contentComponent: SideMenu,
  cardStyle: { backgroundColor: '#FFFFFF'},
  drawerLockMode: 'locked-closed'

}
);


let Navigation = createAppContainer(RootStack);

export default Navigation;

У меня есть следующие настройки в моемсделанное на заказ sidemenu -

mport React, {Component} from 'react';
import CopyrightSpiel from './CopyrightSpiel';
import {ScrollView, Text, View, StyleSheet, Image, Button, TouchableOpacity} from 'react-native';
import { withNavigation } from 'react-navigation';
import { connect } from "react-redux";

import { authLogout, clearUser } from "../../store/actions/index";

class SideMenu extends Component {
  constructor(props) {
    super(props);
    this.state = { loggedIn:false};
  }

  logOutHandler = () => {

    this.props.onTryLogout();
    this.props.clearUser();
    this.props.navigation.navigate('AppContainer');
  };

  render() {
    const isLoggedIn = () => {
      if(this.state.loggedIn){

        return true;
      }
      else {return false; }
    };
    let cp = this.props.activeItemKey;

    let getCurrentCoordinates = (pg) => {
      if(cp === pg){
        return true;
      }
    };

    return (
      <View style={styles.container}>

        <ScrollView>
          <View style={styles.header}>
            <View style={styles.closeBtnWrap}>
              <TouchableOpacity
                onPress={() => this.props.navigation.toggleDrawer() }
              >
                <Image
                  style={styles.closeBtnImg}
                  source={require('../../images/icons/ico-close.png')}
                />

              </TouchableOpacity>
            </View>


            <View style={styles.logoBlock}>
              <Image style={styles.homeBlockImg} source={require('../../images/loginLogo.png')} />
            </View>

          </View>
          <View style={styles.navSection}>

            <TouchableOpacity
              onPress={() => this.props.navigation.navigate('HomeViewContainer')}
            >
              <View style={[styles.navSectionStyle, getCurrentCoordinates('HomeViewContainer') && styles.navItemSel]}>
                <Text style={styles.navItemStyle}>
                HOME
                </Text>
              </View>
            </TouchableOpacity>

            <TouchableOpacity
              onPress={() => this.props.navigation.navigate('RotaContainer')}
            >
              <View style={[styles.navSectionStyle, getCurrentCoordinates('RotaContainer') && styles.navItemSel]}>
                <Text style={styles.navItemStyle} >
                MY ROTA
                </Text>
              </View>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => this.props.navigation.navigate('LrmDocsContainer')}
            >
              <View style={[styles.navSectionStyle, getCurrentCoordinates('LrmDocsContainer') && styles.navItemSel]}>
                <Text style={styles.navItemStyle} >
                LRM DOCS
                </Text>
              </View>
            </TouchableOpacity>

            <TouchableOpacity onPress={this.logOutHandler}>
              <View style={styles.navSectionStyle}>
                <Text style={styles.navItemStyle} >
                SIGN OUT
                </Text>
              </View>
            </TouchableOpacity>
          </View>

          <View style={styles.navSection}>

            <Text style={styles.navSectionTitle}>Current Shift Options:</Text>
            <TouchableOpacity
              onPress={() => this.props.navigation.navigate('CheckInContainer')}
            >
              <View style={[styles.navSectionStyle, isLoggedIn() && styles.checkedInHide, getCurrentCoordinates('CheckInContainer') && styles.navItemSel]}>
                <Text style={styles.navItemStyle} >
                CHECK IN
                </Text>
              </View>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => this.props.navigation.navigate('CheckInContainer')}
            >
              <View style={[styles.navSectionStyle, !(isLoggedIn()) && styles.checkedOutHide, getCurrentCoordinates('CheckInContainer') && styles.navItemSel]}>
                <Text style={styles.navItemStyle} >
                CHECK OUT
                </Text>
              </View>
            </TouchableOpacity>

          </View>
        </ScrollView>
        <View style={styles.footerContainer}>
          <CopyrightSpiel color="LightGrey"/>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  header:{
    flexDirection:'row',

    justifyContent:'center',
  },
  closeBtnWrap:{
    position:'absolute',
    left:15,
    top:0,
    opacity:0.8,
  },
  closeBtnImg:{
    width:22,
    height:22

  },
  container:{
    backgroundColor:'#1C2344',
    alignSelf:'stretch',
    flex:1,
    paddingTop:50,
    borderLeftColor:'#F7931E',
    borderLeftWidth:1
  },
  logoBlock:{
    alignSelf:'center',

  },

  homeBlockImg:{
    marginTop:10,
    width:60,
    height:105,

  },
  navSectionStyle:{
    alignItems:'stretch',
    textAlign: 'center',
    backgroundColor:'rgba(255,255,255,0.1)',
    paddingTop:8,
    paddingBottom:8,
    marginTop:15,
  },
  navItemSel:{
    backgroundColor:'rgba(255,255,255,0.9)',
  },
  navItemSelText:{
    color:'#1C2344',
  },
  navItemStyle:{
    color:'#F7931E',
    fontSize:24,
    alignSelf:'center'

  },
  navSection:{
    marginTop:30

  },
  navSectionTitle:{
    color:'rgba(255,255,255,0.5)',
    marginLeft:15,

  },
  footerContainer:{
    paddingBottom:15,
  },
  checkedInHide:{
    display:'none',
  },
  checkedOutHide:{
    display:'none',
  },

});

const mapDispatchToProps = dispatch => {
  return {
    onTryLogout: () => dispatch(authLogout()),
    clearUser: () => dispatch(clearUser())
  };
};

export default connect(null, mapDispatchToProps)(withNavigation(SideMenu));

, который отлично работает -

В моем подзаголовке у меня есть следующее:

    import React from 'react';
import {View, Image, Text, StyleSheet, TouchableOpacity, Button} from 'react-native';
import PropTypes from 'prop-types';
import { withNavigation } from 'react-navigation';
import { StackActions } from 'react-navigation';



class FixedHeader extends React.Component {
  render() {
    const popAction = StackActions.pop({
      n: 0,
    });
    return (

      <View style={FixedHeaderStyles.sectionHeader}>
        <View style={FixedHeaderStyles.sectionHeaderTopLine}>
          <View style={[FixedHeaderStyles.sectionHeaderBack, !(this.props.backButton) && FixedHeaderStyles.sectionHeaderHide ]}>



            <TouchableOpacity
              onPress={() =>   this.props.navigation.dispatch(popAction)}
            >
              <Text style={FixedHeaderStyles.sectionHeaderText}>&#x3c; Back</Text>
            </TouchableOpacity>
          </View>
          <View style={FixedHeaderStyles.logoBlock}>
            <Image style={FixedHeaderStyles.homeBlockImg} source={require('../../images/logosmall.png')} />
          </View>
          <View style={FixedHeaderStyles.homeBlockBurger} >

            <TouchableOpacity  onPress={() => this.props.navigation.toggleDrawer() }>

              <Image
                style={FixedHeaderStyles.homeBurgerImg}
                source={require('../../images/icons/ico-burger.png')}
              />

            </ TouchableOpacity>
          </View>
        </View>

      </View>
    );
  }
}

FixedHeader.propTypes = {
  backButton: PropTypes.bool.isRequired,
  navigate: PropTypes.object,
};

const FixedHeaderStyles = StyleSheet.create({
  sectionHeadeLogo:{

    width:45,
    height:58,
    alignSelf:'center'

  },
  sectionHeader:{
    backgroundColor:'#1C2344',
    flex:1.8,
    alignSelf:'stretch',
    borderBottomColor:'#f79431',
    borderBottomWidth:1,
  },
  sectionHeaderTopLine:{
    height:120,
    paddingTop:45,
    borderBottomColor:'#f79431',
    borderBottomWidth:1,
    flexDirection:'row',
    justifyContent:'center',
    alignItems:'center'
  },

  homeBlockBurger:{
    position:'absolute',
    right:0,
    marginRight:15,
    top:56
  },
  logoBlock:{
    alignSelf:'flex-start',
  },
  homeBlockImg:{
    width:45,
    height:58,
    alignSelf:'center',

  },
  homeBurgerImg:{
    width:40,
    height:40,
  },
  sectionHeaderHide:{
    display:'none',

  },
  sectionHeaderBack:{
    position:'absolute',
    left:15,
    top:70,
  },
  sectionHeaderText:{
    color:'#fff',
  },


});


export default withNavigation(FixedHeader);

Страница прекрасно перемещается кподпредставление - но при нажатии назад страница переходит к корню (странице входа), а не к предыдущей странице.Например - я перехожу к повороту из дома, нажимаю назад и возвращаюсь к входу в систему ... может кто-нибудь пролить свет на это и указать мне правильное направление - я прочитал документацию, но не могу понять, что сбивается с пути ...

Мои зависимости следующие:

enter image description here

Ответы [ 3 ]

0 голосов
/ 01 апреля 2019

Вы не должны определять свой popAction с индексом 0 в вашем FixedHeader классе.

const popAction = StackActions.pop({
      n: 0,
    });

вместо этого попробуйте

const popAction = StackActions.pop();

Всплывающее действие возвращает вас к предыдущему экрану в стеке.

Параметр n позволяет указать, сколько экранов будет отображаться на.

Пожалуйста, обратитесь к этим документам: https://reactnavigation.org/docs/en/stack-actions.html#pop

Кроме того, вам лучше определить const popAction = ... вне render() метода.

import React from 'react';
import {View, Image, Text, StyleSheet, TouchableOpacity, Button} from 'react-native';
import PropTypes from 'prop-types';
import { withNavigation } from 'react-navigation';
import { StackActions } from 'react-navigation';

const popAction = StackActions.pop(); 
class FixedHeader extends React.Component {

  render() {
    return (

      <View style={FixedHeaderStyles.sectionHeader}>
        <View style={FixedHeaderStyles.sectionHeaderTopLine}>
          <View style={[FixedHeaderStyles.sectionHeaderBack, !(this.props.backButton) && FixedHeaderStyles.sectionHeaderHide ]}>



            <TouchableOpacity
              onPress={() =>   this.props.navigation.dispatch(popAction)}
            >
              <Text style={FixedHeaderStyles.sectionHeaderText}>&#x3c; Back</Text>
            </TouchableOpacity>
          </View>
          <View style={FixedHeaderStyles.logoBlock}>
            <Image style={FixedHeaderStyles.homeBlockImg} source={require('../../images/logosmall.png')} />
          </View>
          <View style={FixedHeaderStyles.homeBlockBurger} >

            <TouchableOpacity  onPress={() => this.props.navigation.toggleDrawer() }>

              <Image
                style={FixedHeaderStyles.homeBurgerImg}
                source={require('../../images/icons/ico-burger.png')}
              />

            </ TouchableOpacity>
          </View>
        </View>

      </View>
    );
  }
}

FixedHeader.propTypes = {
  backButton: PropTypes.bool.isRequired,
  navigate: PropTypes.object,
};

const FixedHeaderStyles = StyleSheet.create({
  sectionHeadeLogo:{

    width:45,
    height:58,
    alignSelf:'center'

  },
  sectionHeader:{
    backgroundColor:'#1C2344',
    flex:1.8,
    alignSelf:'stretch',
    borderBottomColor:'#f79431',
    borderBottomWidth:1,
  },
  sectionHeaderTopLine:{
    height:120,
    paddingTop:45,
    borderBottomColor:'#f79431',
    borderBottomWidth:1,
    flexDirection:'row',
    justifyContent:'center',
    alignItems:'center'
  },

  homeBlockBurger:{
    position:'absolute',
    right:0,
    marginRight:15,
    top:56
  },
  logoBlock:{
    alignSelf:'flex-start',
  },
  homeBlockImg:{
    width:45,
    height:58,
    alignSelf:'center',

  },
  homeBurgerImg:{
    width:40,
    height:40,
  },
  sectionHeaderHide:{
    display:'none',

  },
  sectionHeaderBack:{
    position:'absolute',
    left:15,
    top:70,
  },
  sectionHeaderText:{
    color:'#fff',
  },


});

export default withNavigation(FixedHeader);

Приветствия

0 голосов
/ 02 апреля 2019

После большого количества голов и царапин - я нашел ответ на свой вопрос - Моя проблема в том, что я использую навигацию по ящику, а не стековую навигацию - всплывающее окно не доступно для ящика, так как нет доступного стека -

ref - https://reactnavigation.org/docs/en/navigation-prop.html

ответ от - https://github.com/react-navigation/react-navigation/issues/4793

0 голосов
/ 01 апреля 2019

Поскольку вы используете withNavigation HOC, вы захотите использовать navigation prop в вашем FixedHeader компоненте вместо вызова StackActions.pop. Вы можете просто позвонить this.props.navigation.pop().

https://reactnavigation.org/docs/en/navigation-prop.html#navigator-dependent-functions

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...