首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在react native中导航到登录按钮的主屏幕onPress?

如何在react native中导航到登录按钮的主屏幕onPress?
EN

Stack Overflow用户
提问于 2018-05-29 05:07:20
回答 2查看 1.7K关注 0票数 1

onPress的登录按钮,我想导航到其他一些屏幕,基本上是一个主屏幕的身份验证采取用户名和密码。我使用的是一个stack navigator,但当我点击登录按钮时,它只是点击了应用程序接口,什么也没有发生。

下面是我的代码:

代码语言:javascript
复制
  import React, { Component } from 'react';
   import {
     StyleSheet,
     Platform,
     Text,
     Image,
     View,TouchableOpacity,ImageBackground,ScrollView,AsyncStorage
   } from 'react-native';

   const instructions = Platform.select({
     ios: 'Press Cmd+R to reload,\n' +
       'Cmd+D or shake for dev menu',
     android: 'Double tap R on your keyboard to reload,\n' +
       'Shake or press menu button for dev menu',
   });

   import { TabNavigator, StackNavigator } from 'react-navigation';
   import Icon from 'react-native-vector-icons/Ionicons';
   import EvilIcons from 'react-native-vector-icons/EvilIcons';
   import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
   import { Container, Header, Content, Card, CardItem, Thumbnail, Button, Left, Body, Right, Item, Input } from 'native-base';

访问令牌:

代码语言:javascript
复制
    const ACCESS_TOKEN = 'access_token';
    export default class Landing extends Component {
        static navigationOptions = { 
            header: false
            };
       constructor(props) {
          super(props);
          this.state = {
            username: "",
            password: "",
            error: "",
          };  
        }

      async storeToken(accessToken){
        try{
            await AsyncStorage.setItem(ACCESS_TOKEN, access_token)
            this.getToken();
        } catch (error) {
          console.log("Something went wrong")
        }
      }

      async getToken(accessToken){
        try{
            let token = await AsyncStorage.getItem(ACCESS_TOKEN)
           console.log("token is: " + token)
        } catch (error) {
          console.log("Something went wrong")
        }
      }

      async removeToken(){
        try{
          await AsyncStorage.getItem(ACCESS_TOKEN)
           console.log("token is: " + token)
           this.getToken();
        } catch (error) {
          console.log("Something went wrong")
        }
      }

数据拉取:

代码语言:javascript
复制
      async onLoginPressed() {
        this.setState({showProgress: true})
        try {      
          let response = await fetch('https://fb3b2e18.ngrok.io/login', {
                      method: 'POST',
                      headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                      },
                      body: JSON.stringify({
                          username: this.state.username,
                          password: this.state.password,
                      })
                    });
          let res = await response.text();
          if (response.status >= 200 && response.status < 300) {
              //Handle success
              this.setState({error: ""});
              let accessToken = res;
              this.storeToken(accessToken);
              console.log( "res token: " +  accessToken);
              //On success we will store the access_token in the AsyncStorage
              this.storeToken(accessToken);
          } else {
              //Handle error
              let error = res;
              throw error;
          }
        } catch(error) {
            this.removeToken();
            this.setState({error: error});
            console.log("error " + error);
        }
      }

渲染

方法

代码语言:javascript
复制
        render() {
          const {goBack} = this.props.navigation;
          var {navigate} = this.props.navigation;
            return (
                <ImageBackground source={require('./landing.png')} style={styles.backgroundImage}>              
                  <ScrollView automaticallyAdjustContentInsets={false} style={styles.scrollView}>   
                     <Text style={styles.welcome}>
                        Welcome to Flipclip
                      </Text>                                     
                      <View style={{alignItems: 'center', flex: 1,marginBottom: 60}}>                      
                        <Item style={{width: 310,marginBottom: 10}}>
                          <EvilIcons style={{color:'#fefefe'}} name='user' size={20} />
                          <Input 
                            style={{color: '#f5f5f5',fontSize: 14,fontFamily: 'Montserrat-Regular',}} 
                            placeholder='User Name'
                            placeholderTextColor= '#f5f5f5' 
                            onChangeText={ (text)=> this.setState({username: text}) }
                          />
                        </Item>                     
                        <Item style={{width: 310}}>
                          <Icon style={{color:'#fefefe'}} name='ios-lock-outline' size={20}/>
                          <Input 
                            style={{color: '#f5f5f5',fontSize: 14, marginLeft: 5,fontFamily: 'Montserrat-Regular',}} 
                            placeholder='Password'
                            placeholderTextColor= '#f5f5f5' 
                            onChangeText={ (text)=> this.setState({password: text}) }
                          />
                        </Item>
                      </View>
                      <View style={{alignSelf: 'center', flex: 1}}>
                        <Button block transparent style={styles.LoginButton} onPress = {this.onLoginPressed.bind(this)}  >
                          <Text style={styles.logintext}>Sign In</Text>
                        </Button>
                      </View>                  
                      <View style={{justifyContent: 'center'}}>
                        <Text style={styles.SignUpResendOtpText}>
                          Don’t have an account?&nbsp;
                          <Text style={styles.SignUpResendOtpLink} onPress = { () => navigate ("SignUp", {}) }>
                            Sign Up
                          </Text>
                        </Text>
                      </View>

                      <Text style={styles.error}>
                        {this.state.error}
                      </Text>
                  </ScrollView>
                </ImageBackground>
            )
        }
    }

样式:

代码语言:javascript
复制
    const styles = StyleSheet.create({
        scrollView:{
          backgroundColor: 'rgba(0,0,0,0.7)', 
          flex:1,
        },
        backgroundImage: {
            flex: 1,
            width: null,
            height: null,
        },

        text: {
            color: 'white',
            fontSize: 32,
        },

      uploaderName:{
        fontSize: 16,
        color: '#fefefe'
      },
      welcome: {
        fontSize: 28,
        color: '#f5f5f5',
        textAlign: 'center',
        marginTop: 201,
        marginBottom: 135,
        fontFamily: 'FredokaOne-Regular'
      },
      instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
      },
      LoginButton: {
        borderRadius:100,
        backgroundColor: '#ff0046',
        width: 310, 
        marginBottom: 20,
      },
      logintext:{
        color: '#f5f5f5', 
        fontSize: 14,
        fontFamily: 'Montserrat-Medium',
      },
      error: {
        color: 'red',
        paddingTop: 10
      },
      SignUpResendOtpText: {
          color: '#f5f5f5',
          textAlign: 'center',
          fontSize: 14,
          fontFamily: 'Montserrat-Regular',
      },
      SignUpResendOtpLink:{
          color: '#ff0046',
          textAlign: 'center',
          fontSize: 14,
          fontFamily: 'Montserrat-Medium',
          textDecorationLine: 'none',
          textDecorationStyle: 'solid',
          textDecorationColor: '#000'
      },
      success: {
        color: 'green',
        paddingTop: 10
      },
    });
EN

回答 2

Stack Overflow用户

发布于 2018-05-29 09:04:47

在此之前

代码语言:javascript
复制
<Button block transparent style={styles.LoginButton} onPress = {this.onLoginPressed.bind(this)}  >

之后

代码语言:javascript
复制
<Button block transparent style={styles.LoginButton} onPress = { () => this.onLoginPressed.bind(this) }  >
票数 1
EN

Stack Overflow用户

发布于 2019-06-05 18:17:32

我正在使用堆栈导航器,但当我单击登录按钮时,它只是点击api,没有任何反应。

这是因为您按应该的方式点击了api,但是一旦登录凭证成功,您就无法导航到应用程序主屏幕。

所以你错过了这个:

代码语言:javascript
复制
  if (response.status >= 200 && response.status < 300) {
          //Handle success
          this.setState({error: ""});
          let accessToken = res;
          this.storeToken(accessToken);
    // once successful navigate to another screen
    this.props.navigation.navigate('yourScreen',{}}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50573410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档