t-comb-form-native и логическое выражение для принятия условий - PullRequest
0 голосов
/ 28 января 2020

У меня форма регистрации работает отлично, хорошо! Но я хочу создать логическое поле: «термины», и я хочу, чтобы при нажатии на него оно позволяло проверять форму. Но когда не нажали, вы не можете зарегистрироваться. Я не знаю, как мне удастся это сделать.

Моя идея заключалась в том, чтобы поставить условие «если условия приняты, то => форма подтверждена, и вы можете go зайти в свою учетную запись». Мне кажется, что это правильный путь, но я не знаю, как я могу это сделать. Может быть, при создании постоянных терминов, как я сделал для электронной почты, телефона и пароля, но как написать, что он должен быть подтвержден для регистрации? может быть с чем-то вроде «принято ложно» в состоянии, но я не знаю, как вставить «принятые» опции в поле «условия» ...

Спасибо за любую помощь.

import React, { Component } from "react";
import {
  ScrollView,
  View,
  StyleSheet,
  Text,
  ImageBackground,
  AsyncStorage
} from "react-native";
import styles from "../../assets/Styles/Styles";
import i18n from "../../src/i18n";
import { storeProfileToken } from "../../src/common/util/MyPreferences";
import Button from "react-native-flat-button";
import {
  API_URL,
  API_SECRETKEY
} from "../../src/common/util/Constants";
import t from "tcomb-form-native";
import stylesheet from "../../assets/Styles/FormStyles";
import base64 from 'react-native-base64'

const Form = t.form.Form;

const Email = t.refinement(t.String, email => {
  const reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; //or any other regexp
  return reg.test(email);
});

const Phone = t.refinement(t.maybe(t.String), phone_number => {
  const reg = /^(?:\+\d{1,3}|0\d{1,3}|00\d{1,2})?(?:\s?\(\d+\))?(?:[-\/\s.]|\d)+$/; //or any other regexp
  return reg.test(phone_number);
});

const Pwd = t.refinement(t.String, password => {
  const reg = /^(?=.{8,})/; //or any other regexp
  return reg.test(password);
});

const User = t.struct({
  email: Email,
  password: Pwd,
  phone_number: Phone,
  terms: t.Boolean
});

const formStyles = {
  ...Form.stylesheet
};

const options = {
  fields: {
    email: {
      label: i18n.t("signup.input.email"),
      error: i18n.t("signup.error.email")
    },
    password: {
      password: true,
      secureTextEntry: true,
      label: i18n.t("signup.input.password"),
      error: i18n.t("signup.error.password")
    },
    phone_number: {
      label: i18n.t("signup.input.phone"),
      error: i18n.t("signup.error.phone")
    },
    terms: {
      label: i18n.t("signup.input.terms"),
      error: i18n.t("signup.error.terms")
    }
  },
  stylesheet: stylesheet
};

export default class Signup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showProgress: null,
      email: "",
      password: "",
      phone_number: "",
      error: "",
      accepted :false
    };
  }

  async onRegisterPressed(email, pwd, phone, term) {
    //console.log("SIGNUP::email: ", email);
    //console.log("SIGNUP::email: ", pwd);
    //console.log("SIGNUP::email: ", phone);
    //console.log("SIGNUP::email: ", term);

    if (email != "" && pwd != "") {
      this.setState({ showProgress: true });
      try {
        let response = await fetch(
          API_URL +
            "/users?society_id=131&access_token=" +
            "accessToken" +
            "&lang=fr",
          {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              Authorization: "Bearer " + API_SECRETKEY
            },
            body: JSON.stringify({
              email: email,
              password: pwd,
              mobilephone: phone
            })
          }
        )
          .then(response => response.json())
          .then(responseData => {
            //console.log("YOU HAVE SUCCESFULLY LOGGED IN:", responseDocs)
            console.log("ok: ", responseData.status);

            if (responseData.status >= 200 && responseData.status < 300) {
              console.log("data: ", responseData.data);

              //Handle success
              let accessToken = responseData;
              console.log(accessToken);
              //On success we will store the access_token in the AsyncStorage
              this.storeProfileToken(accessToken);
              this.redirect(MyTrips);
            } else {
              //Handle error
              console.log("data-error: ", responseData.data.error);
              let error = responseData;
              throw responseData.data.error;
            }
          });

        return result;
      } catch (error) {
        this.setState({ error: error });
        console.log("error " + error);
        this.setState({ showProgress: false });
      }
    }
  }

  handleSubmit = async () => {
    const data = this._form.getValue();
    //console.log("SIGNUP::data: ", data);

    if (data && data.email && data.password && data.terms) {
      this.onRegisterPressed(
        data.email,
        data.password,
        data.phone_number,
        data.terms
      );
    } /*else if (terms = ok) {
      this.setState({accepted:true})
    } else {this.props.navigation.navigate("Authentication")}*/
  };
  render() {
    return (
      <ImageBackground
        source={require("../../assets/images/bg_mobile_paysage.jpg")}
        style={{ flex: 1 }}
      >
        <ScrollView>
        <View style={styles.container}>
          <Text style={styles.h5}>{"\n"}</Text>
          <Text style={styles.h1}>{i18n.t("signup.title")}</Text>
          <Text style={styles.h5}>{"\n"}</Text>
          <Form ref={c => (this._form = c)} type={User} options={options} />
          <Button
            containerStyle={[styles.mybtnContainer]}
            style={styles.mybtn}
            onPress={this.handleSubmit}
          >
            {i18n.t("signup.action.subscribe").toUpperCase()}
          </Button>
          <Button
            onPress={() => this.props.navigation.navigate("Login")}
            containerStyle={[styles.mybtnContainer, styles.btnContainerMuted]}
            style={styles.mybtn}
          >
            {i18n.t("signup.action.haveAccount").toUpperCase()}
          </Button>
          </View>
        </ScrollView>
      </ImageBackground>
    );
  }
}

1 Ответ

0 голосов
/ 28 января 2020

Я добавил в состоянии «принято: ложь», чтобы передать его значение «истина» при нажатии на термины «this.setState ({принято: истина});» *

  handleSubmit = async () => {
    const data = this._form.getValue();

    if (
      data &&
      data.email &&
      data.password &&
      data.terms &&
      data.terms === false
    ) {
      return;
    } else if (data && data.email && data.password && data.terms) {
      console.log("SIGNUP::term: ", data.terms);
      this.setState({ accepted: true });
      this.onRegisterPressed(
        data.email,
        data.password,
        data.phone_number,
        data.terms
      );
    } /*
  } else {this.props.navigation.navigate("Authentication")}*/
  };

Возможно, это может помочь кому-то в будущее

...