Переход от вкладки к следующему экрану стека не работает - PullRequest
0 голосов
/ 31 января 2019

От индекса до всплеска => до дома его работает.Домашний компонент имеет 2 вкладки, и каждая вкладка имеет плоский список, и я хочу перейти к следующему экрану или компоненту стека из щелчка элемента FlatList из компонента Tab_One ....

Индексный компонент

   const Drawer = DrawerNavigator(
          {
            Home: { screen: Home },
          } ,
          {
            initialRouteName: "Home",
            contentOptions: {
              activeTintColor: "#e91e63"
            },
            contentComponent: props => <SideBar {...props} />
          }
        );

        Drawer.navigationOptions = ({ navigation }) => ({
          header: null
        });


        const AppNavigator = StackNavigator(
          {
            //user define props
            Splash: { screen: Splash },
            Login:  { screen: Login },
            List:   { screen: List },
            Card:   { screen: Card },
            Home:   { screen: Home },
            Drawer: { screen: ({navigation}) => <Drawer screenProps={{rootNavigation: navigation}} />
          }
          },
          {
            index: 0,
            initialRouteName: "Splash",
            headerMode: "none"
          }
        );


        export default class CustomDrawer extends Component {
          componentDidMount() {

             // this.getData();
           }
          render () {
            return (
              <AppNavigator />
            );
          }

          saveData(){
          try {
              let obj = {
                name : 'waleediqbal',
                refreshtoken : 'fsdffsdfsd' ,
                accesstoken : 'erter' ,
                username : 'waleed@iqbal' ,
                password : '123456',
                email : 'waleed@cogilent.com',

              };
               alert("Task added successfully");
              AsyncStorage.setItem('user', JSON.stringify(obj));
            }
           catch (e) {
            alert(e);
          }
        }

          getData() {
          helpers.getUser().then((value) => {
                  alert(JSON.parse(value).email);
                }).done();
            }
        }
        AppRegistry.registerComponent('Far', () => CustomDrawer);

Компонент Splash (он перемещается в Drawer, определенный в stacknavigator, означает, что он фактически перемещается в Home Component отсюда)

    export default class Splash extends Component {

      componentDidMount(){
        setTimeout(()=>{

            helpers.getUser().then((value) => {
              if(value===null){
                 console.log("login","null");
                const UserData =  {"id":null, "email": null,"login":"false"};
                helpers.saveUser(UserData);
                this.props.navigation.replace("Login");
              }
              else if(JSON.parse(value).login==="false"){
                console.log("login","false");
                this.props.navigation.replace("Login");
              }
              else{
                  console.log("login","smooth");
                  this.props.navigation.replace("Drawer");
              }
            }).done();

        },1000);
      }
      render() {
        return (
          <View style={styles.container}>
            <StatusBar
              barStyle="light-content"
              backgroundColor="#4F6D7A"
            />
            <Text style={styles.welcome}>
              Welcome to React Native!
            </Text>
            <Text style={styles.instructions}>
              To get started, edit App.js
            </Text>
            <Text style={styles.instructions}>
              {instructions}
            </Text>
          </View>
        );
      }

    }

Домашний компонент (содержит 2 вкладки, определенные в этом компоненте)

const AccountTabNav = TabNavigator(
{
Tab_One:
  {
  screen: Tab_One,
  navigationOptions: {
  title: "Running"
 }
},
Tab_Two:
  {
  screen: Tab_Two,
  navigationOptions: {
  title: "Completed" }
  }
},
{
  tabBarOptions : {
    activeTintColor: 'white',
    style: {
      backgroundColor: '#002D62',

    },
    indicatorStyle: {
            backgroundColor: 'white',
        }
  }
},
{
backBehavior: "none",
tabBarPosition: "top"
}
);
export default class Home extends Component {

    static navigationOptions = ({ navigation }) => {
        return
        {
         headerLeft: (
             <View style={{ padding: 10 }}>
                 <Ionicons name="md-menu" size={24} onPress={() => navigation.navigate('DrawerOpen')} />
             </View>
         )
     }

    }
    render() {
        return (
          <Container>
          <Header style = {{ backgroundColor: '#FFFFFF' }}>
            <Left>
              <Button
                transparent
                onPress={() => this.props.navigation.navigate("DrawerOpen")}
              >
                <Icon name="menu" style={{color :'#002D62', size : 30}}/>
              </Button>
            </Left>
            <Body>
            <Title style = {{ color : '#002D62',fontSize: 20, fontWeight: 'bold'}}>Khata</Title>
            </Body>

          </Header>
            <AccountTabNav screenProps={{ navigation: this.props.navigation }} />
        </Container>

        )
    }
}

Tab_One (первая вкладка, определенная в компоненте вкладки. Она содержит список, и я хочу перейти от щелчка по спискуэлемент на другой экран компонента стека, но он не работает, не вызывает ошибок, но не перемещается)

export default class Tab_One extends Component {

  constructor(props) {
    super(props);
    this.state = {
         runningList: null,
         loading: true,
         userid: null,
         refreshing : false
     }
     this.renderItem = this.renderItem.bind(this);
     this._onPress = this._onPress.bind(this);
  }
  async componentDidMount() {

   const value = await AsyncStorage.getItem("UserData");
   this.setState({userid:  JSON.parse(value).id});

   const runningApiCall = await fetch('https://opmlfar.net/api/audit', {
     method: 'POST',
     headers: {
       Accept: 'application/json',
       'Content-Type': 'application/json',
     },
     body: JSON.stringify({
       user_id : this.state.userid,
     }),
     });

    try {
      const running = await runningApiCall.json();
      console.log("data-", running);
      this.setState({runningList: running, loading: false});
      this.onStop();
    }
    catch(err) {
      console.log("Error fetching data-----------", err);
      this.onStop();
    }

  }
  actionOnRow(item) {
     console.log('Selected Item :',item);
     Alert.alert('You tapped the button!');
  }
  _onPress (id){
    console.log('Selected Item :');
    alert(this.props.navigation.state);
    console.log(this.props.navigation.state);
    this.props.screenProps.navigation.navigate('Card');

  }

  onRefresh = ()=>{
        this.setState({refreshing : true});
        this.componentDidMount();
    }
  onStop = ()=>{
          this.setState({refreshing : false});
  }

  renderItem(data) {
          return <TouchableOpacity style={{backgroundColor: 'transparent'}}  onPress= {()=>  this.props.screenProps.navigation.navigate('Card')}>
                    <Card flexDirection='column' >
                       <View style={{flex: 1,flexDirection:'row',left:10,marginTop:10}}>
                         <Icon  color='#BDC3C7' name='adjust' size={15} style={{height:18}} />
                         <Text style={{fontSize:16, fontWeight:'bold', marginLeft:10 , flex:0.9, color:'#002D62'}}>
                           {data.item.project.name}
                         </Text>
                         <Icon  color='#002D62' name='settings' size={25} style={{ height:18, flex:0.1, justifyContent: "right",alignItems: "right" }} />
                       </View>
                       <View style={{flex: 1,flexDirection:'row',left:16, marginTop:0, marginBottom:2}}>
                         <Dash dashColor= '#BDC3C7' style={{width:1, height:23, flexDirection:'column', overflow: 'hidden'}}/>
                         <Text style={{fontSize:14, fontWeight:'normal',marginLeft:21, flex:0.7, justifyContent: "center",alignItems: "center" }}>
                           {data.item.start_date}  |  {data.item.end_date}
                         </Text>
                       </View>
                       <View style={{flex: 1,flexDirection:'row',left:10,marginBottom:10}}>
                         <Icon name='place' color='#BDC3C7' size={15}/>
                         <Text style={{ fontSize:14, fontWeight:'bold', marginLeft:12, marginTop:-2, color :'#797D7F'}} >
                           {data.item.status_name}
                         </Text>
                       </View>
                    </Card>
                 </TouchableOpacity>
      }
  render() {
     const { navigation, screenProps } = this.props
     const { runningList, loading } = this.state;
        if(!loading) {
          return (
                <Container>
                  <Content padder>
                  <TouchableHighlight onPress={this.onRefresh}>
                  <Text style={{fontSize:14, fontWeight:'normal', marginRight:10 ,textAlign: 'right', alignSelf: 'stretch', flex:0.9, color:'#002D62',marginBottom:5}}>
                    Refresh
                  </Text>
                  </TouchableHighlight>
                  <ScrollView
                     refreshControl={
                       <RefreshControl
                         refreshing={this.state.refreshing}
                         onRefresh={this.onRefresh}
                       />
                     }

                   >
                   <FlatList
                     data={runningList.audits}
                     renderItem={this.renderItem}
                     keyExtractor={(item) => item.id}
                     refreshing ={this.state.refreshing}
                     onRefresh ={this.onRefresh}
                     />
                     </ScrollView>
                  <Image
                      source={require("./../../../assets/fireworks.gif")}
                      style={styles.image}
                    />
                  </Content>
                </Container>
        );
        } else {
            return <ActivityIndicator size="large" color="#002D62" style= {{marginTop:10}}/>
        }
  }

}

Blockquote

...