Как переназначить страницу при нажатии кнопки ОК - PullRequest
0 голосов
/ 20 февраля 2020

Здесь, в моем коде, я пытаюсь перезагрузить страницу при нажатии кнопки ОК. Но это не работает. Как я могу изменить страницу на кнопку ОК, это написано на той же странице, которую я должен перезагрузить. В моем коде я спою форму и compont поля ввода для моего экрана входа в систему. Весь код там ниже. Я пытаюсь, чтобы, когда я получаю любой ответ, как неправильное имя пользователя и пароль в alere, тогда кнопка ОК, я должен очистить свое поле формы. Пока вот это не радует. Для этого я удаляю свою ценность вручную. Пожалуйста, добавьте.

   import React from 'react';
import { Alert, Dimensions, ImageBackground, Text, View, TouchableOpacity, Platform , StatusBar} from 'react-native';
import  Formbox from './ui/form';
import { RegularText, } from './ui/text';
import pkg from '../../package';
import _ from 'lodash';
import { LOGIN_BACKGROUND , LOGIN_BACKGROUND_DARK} from '../images'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import parentStyle from '../themes/parent.style'
import LottieView from 'lottie-react-native';



const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;

const styles = {
  imgBG: { width: '100%', height: '100%' },
  mainContainer: {
    flex: 1,
    alignItems: 'stretch',
    justifyContent: 'flex-start',
    height: deviceHeight,
    paddingLeft: 20,
    paddingRight: 20
  },
  logoContainer: { justifyContent: 'center', alignItems: 'center', background: 'red', marginTop: -50 },
  logoView: {
    borderWidth: 3,
    borderColor: '#FFFFFF',
    borderRadius: 4,
    zIndex: -1,
    ...Platform.select({
      ios: {
        shadowOpacity: 0.45,
        shadowRadius: 3,
        shadowColor: '#090909',
        shadowOffset: { height: 1, width: 0 }
      },
      android: {
        elevation: 3
      }
    })
  }
};

export default class Login extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.error) {
      if (this.props.error.graphQLErrors[0] !== undefined) {
        const errorDetails = _.map(_.split(this.props.error.graphQLErrors[0].message, '#'), _.trim)
        const header = errorDetails[0];
        const message = errorDetails[1];
        Alert.alert(header, message, [{
          text: 'OK',
          onPress: () => this.props.navigation.push('Auth')
        },]);
      } else {
        Alert.alert('Network Error', this.props.error.networkError.message, [{
          text: 'OK',
          onPress: () => this.props.navigation.navigate('Auth')
        },]);
      }
    }
  }
  componentDidMount(){
    StatusBar.setBarStyle('dark-content');
  }

  render() {
    let loginForm = [
      { label: 'Username', icon: 'person', type: 'text' },
      { label: 'Password', icon: 'key', type: 'password' }
    ];
    let submitBtn = { label: 'Login', OnSubmit: this.props.onLogin };
    let appliedTheme = this.props.theme;
    let appliedMode = this.props.mode;
    return (
      <ImageBackground source={appliedMode === 'light' ? LOGIN_BACKGROUND : LOGIN_BACKGROUND_DARK} style={styles.imgBG}>
        <View style={styles.mainContainer}>
          <View style={{ flexDirection: 'column', alignContent: 'center', justifyContent: 'center', flex: 1 }}>
            <View style={{ flex: 0.75, justifyContent: 'center' }}>
              <RegularText text={'Welcome,'} textColor='#57606F' style={{ fontSize: hp('5%') }} />
              <RegularText text={'Sign in to continue'} textColor='#ABAFB7' style={{ fontSize: hp('3.5%') }} />
            </View>
            <View style={{ flex: 2 }}>
              <View style={{ flex: 2 }}>
                <Formbox
                  theme={parentStyle[appliedTheme] ? parentStyle[appliedTheme][appliedMode].primaryButtonColor : undefined}
                  mode={this.props.mode}
                  formFields={loginForm}
                  submit={submitBtn}
                  that={this}
                  mutation={this.props.token}
                />
                <View style={{ height: hp(20), zIndex:10, top: -25}}>
                  {this.props.loading && (
                    <LottieView source={require('./animations/login_authentication.json')} autoPlay loop />
                  )}
                </View>
                <View style={{top:-70,  zIndex:10}}>
                  {false && <View style={{ alignItems: 'center' }}>
                    <RegularText text={`v${pkg.version}`} textColor='#ABAFB7' style={{ fontSize: hp('2%') }} />
                  </View>}
                  <View style={{ alignItems: 'flex-end' }}>
                    <View style={{ flexDirection: 'row' }}>
                      <RegularText text={`New User?`} textColor='#4A494A' style={{ fontSize: hp('2%') }} />
                      <TouchableOpacity>
                        <RegularText text={` REGISTER`} textColor={parentStyle[appliedTheme] ? parentStyle[appliedTheme][appliedMode].primaryButtonColor : '#fff'} style={{ fontSize: hp('2%'), fontWeight: 'bold' }} />
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              </View>
            </View>

          </View>
        </View>
      </ImageBackground>

    );
  }
}

////// Форма, js

import React, { Component } from 'react';
import { View, Platform, Dimensions } from 'react-native';
import { PrimaryBtn,PrimaryAbsoluteGradientBtn } from './buttons';
import { InputField, PasswordField } from './inputField';
import { Form } from 'native-base';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';

const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
export default class Formbox extends Component {
  constructor(props) {
    super(props);
  }

  OnSubmit() {
    let { formFields, that, submit, mutation } = this.props;
    submit.OnSubmit.bind(that, formFields, mutation)();
  }

  OnChange(field, target) {
    this.props.formFields.forEach(function (formField, indx) {
      if (formField.label === field.label) {
        formField.value = target;
      }
    });

  }

  renderFields(field, indx) {
    let { label, icon, type } = field;
    if (label && icon) {
      if (type === 'password') {
        return <PasswordField key={label + indx} type={type ? type : ''} label={label} icon={icon}
          OnChange={this.OnChange} that={this} />;
      }
      return <InputField key={label + indx} type={type ? type : ''} label={label} icon={icon} OnChange={this.OnChange}
        that={this} />;
    }
  }

  render() {
    let { formFields, submit, that , theme, mode} = this.props;
    return (
      <View style={{ width: '100%' }}>
        <Form style={{ width: '95%' }}>
          {formFields.map((field, indx) => this.renderFields(field, indx))}
          <View style={{ marginTop: 60 }}>
            <PrimaryAbsoluteGradientBtn label={submit.label} OnClick={this.OnSubmit} that={this} backgroundColor={theme}/></View>
        </Form>
      </View>
    );
  }
}

/// поля ввода js

import React, { Component } from 'react';
import { Icon, Input, Item, Label } from 'native-base';
import { View } from 'react-native';
import { DoNothing } from '../services/services';

class InputField extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    let { label, OnChange, icon, that,type, keyboardType } = this.props;
    return (
      <View>
        <Item floatingLabel>
          {icon && <Icon active name={icon}/>}
          {label && <Label>{label}</Label>}
          <Input
            secureTextEntry={type === 'password'}
            onChangeText={OnChange ? (e) => OnChange.bind(that, this.props, e)() : DoNothing.bind(this)}
            keyboardType={keyboardType || 'default'}
            autoCapitalize = 'none'
            autoCorrect={false}
          />
        </Item>
      </View>
    );
  }
}

class PasswordField extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isMasked: true
    };
  }

  _toggleMask = () => {
    this.setState({
      isMasked: !this.state.isMasked
    });
  };

  render() {
    let { label, OnChange, icon, that, type } = this.props;
    const { isMasked } = this.state;
    return (
      <View>
        <Item floatingLabel>
          {icon && <Icon active name={icon}/>}
          <Label>{label}</Label>
          <Input
            autoCapitalize = 'none'
            secureTextEntry={isMasked}
            onChangeText={OnChange ? (e) => OnChange.bind(that, this.props, e)() : DoNothing.bind(this)}
          />
          <Icon name={isMasked ? "md-eye-off" : "md-eye"} active  type="Ionicons" onPress={() => this._toggleMask()}/>
        </Item>
      </View>
    );
  }
}

const styles = {
  dark: {
    color: "#000000"
  },
  light: {
    color: "#EAEAEA"
  }
}

export { InputField, PasswordField };

1 Ответ

0 голосов
/ 20 февраля 2020

Вы можете сделать:

onPress: () => this.props.navigation.push('Auth')

или сделать что-то вроде:

onPress: () => this.setState({name:'random'})

Они оба будут запускать рендеринг, надеюсь, это поможет. не стесняйтесь сомнений

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