Проблема стиля на странице аутентификации - PullRequest
0 голосов
/ 06 февраля 2020

Мне нужна помощь, чтобы понять ошибку, которую я допустил в своем коде.

Я сделал страницу аутентификации для пользователей моего приложения. Вы можете подключиться с помощью входа / регистрации и Facebook и Google. Я не знаю, мне удается это сделать, но сверху и снизу моего Google Button есть огромное пространство. Я не понимаю, откуда это ... Не могли бы вы мне помочь? Спасибо за любую помощь / помощь:)

Страница аутентификации изображения

enter image description here

async function logIn() {
  try {
    await Facebook.initializeAsync("id");
    const {
      type,
      token,
      expires,
      permissions,
      declinedPermissions
    } = await Facebook.logInWithReadPermissionsAsync({
      permissions: ["public_profile"]
    });
    if (type === "success") {
      // Get the user's name using Facebook's Graph API
      const response = await fetch(
        `https://graph.facebook.com/me?access_token=${token}`
      );
      Alert.alert("Logged in!", `Hi ${(await response.json()).name}!`);
    } else {
      // type === 'cancel'
    }
  } catch ({ message }) {
    alert(`Facebook Login Error: ${message}`);
  }
}

const LoginPage = props => {
  return (
    <View style={styles.container}>
      <Button
        onPress={() => props.signIn()}
        containerStyle={[styles.mybtnContainer, styles.btnContainerGoogle]}
        contentStyle={styles.buttonAccueil}
      >
        GOOGLE
      </Button>
    </View>
  );
};

const LoggedInPage = props => {
  return (
    <View style={styles.container}>
      <Text style={styles.header}>Welcome:{props.name}</Text>
      <Image source={{ uri: props.photoUrl }} />
    </View>
  );
};

    export default class Authentication extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          signedIn: false,
          name: "",
          photoUrl: ""
        };
      }
      signIn = async () => {
        try {
          const result = await Google.logInAsync({
            androidClientId:
              "10517196-fpp2cg7r886ln73ri03qqdrvdriek33s.apps.googleusercontent.com",
            iosClientId:
              "10596-2n9sl21e06cd36o901f92u3vi07qhd9u.apps.googleusercontent.com",
            scopes: ["profile", "email"]
          });

          if (result.type === "success") {
            this.setState({
              signedIn: true,
              name: result.user.name,
              photoUrl: result.user.photoUrl
            });
          } else {
            console.log("cancelled");
          }
        } catch (e) {
          console.log("error", e);
        }
      };

      render() {
        return (
          <ImageBackground
            source={require("../../assets/images/background.jpg")}
            style={styles.backgroundImage}
          >
            <Header
              centerComponent={{
                text: i18n.t("welcome.title"),
                style: {
                  height: 60,
                  fontFamily: "FunctionLH",
                  fontSize: 30,
                  color: "#fff"
                }
              }}
              containerStyle={{
                marginTop: 0,
                backgroundColor: "#6C6363",
                borderBottomColor: "transparent" }}
              statusBarProps={{ barStyle: "light-content" }}
            />
            <View style={styles.container}>
              <View style={styles.container}>
                {this.state.signedIn ? (
                  <LoggedInPage
                    name={this.state.name}
                    photoUrl={this.state.photoUrl}
                  />
                ) : (
                  <LoginPage signIn={this.signIn} />
                )}
              </View>
              <Button
                onPress={logIn}
                containerStyle={[styles.mybtnContainer, styles.btnContainerFb]}
                contentStyle={styles.buttonAccueil}
              >
                FACEBOOK
              </Button>
              <Button
                onPress={() => this.props.navigation.navigate("Login")}
                containerStyle={styles.mybtnContainer}
                contentStyle={styles.buttonAccueil}
              >
                {i18n.t("welcome.action.login").toUpperCase()}
              </Button>
                <Button
                  onPress={() => this.props.navigation.navigate("Signup")}
                  containerStyle={styles.mybtnContainer}
                  contentStyle={styles.buttonAccueil}
                >
                  {i18n.t("welcome.action.signup").toUpperCase()}
                </Button>
            </View>
          </ImageBackground>
        );
      }
    }

Стили:

container: {
    flex: 1,
    backgroundColor: "transparent",
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
  },
header: {
    fontFamily: "FunctionLH",
    fontSize: 25
  },
  buttonAccueil: {
    fontFamily: "FunctionLH",
    fontSize: 26,
    fontWeight: "900",
    alignItems: "center",
    justifyContent: "center"
  },
mybtnContainer: {
    fontFamily: "FunctionLH",
    marginVertical: 6,
    minWidth: 275,
    height: 50,
    backgroundColor: "rgba(108, 99, 99, .9)",
    borderColor: "#6C6363",
    borderRadius: 100
  },
btnContainerFb: {
    fontFamily: "FunctionLH",
    backgroundColor: "#436AF9",
    borderColor: "#436AF9"
  },
  btnContainerGoogle: {
    fontFamily: "FunctionLH",
    backgroundColor: "#F53838",
    borderColor: "#F53838"
  },

Ответы [ 2 ]

1 голос
/ 06 февраля 2020

Ваша кнопка Google находится отдельно от других кнопок и вложена в несколько компонентов View. Если разобраться, это должно выглядеть лучше. Как минимум: не назначайте стиль контейнера каждому представлению.

Для иллюстрации:

<View>
  <View>
    <View>
      <Button> Google </Button> // inside 3 Views
    </View>
  </View>
  // move Google Button here, use 'this' instead of passing props to LoginPage component
  <Button>Facebook</Button> // inside 1 View
  <Button>Login</Button> // inside 1 View
  <Button>Sign Up</Button> // inside 1 View
</View>
0 голосов
/ 06 февраля 2020

Ты молодец @Sydney Y

Благодаря твоей помощи я изменил свой код таким образом.

async function logIn() {
  try {
    await Facebook.initializeAsync("id");
    const {
      type,
      token,
      expires,
      permissions,
      declinedPermissions
    } = await Facebook.logInWithReadPermissionsAsync({
      permissions: ["public_profile"]
    });
    if (type === "success") {
      // Get the user's name using Facebook's Graph API
      const response = await fetch(
        `https://graph.facebook.com/me?access_token=${token}`
      );
      Alert.alert("Logged in!", `Hi ${(await response.json()).name}!`);
    } else {
      // type === 'cancel'
    }
  } catch ({ message }) {
    alert(`Facebook Login Error: ${message}`);
  }
}

const LoginPage = props => {
  return (
    <View>
      <Button
        onPress={() => props.signIn()}
        containerStyle={[styles.mybtnContainer, styles.btnContainerGoogle]}
        contentStyle={styles.buttonAccueil}
      >
        GOOGLE
      </Button>
    </View>
  );
};

const LoggedInPage = props => {
  return (
    <View>
      <Text style={styles.header}>Welcome:{props.name}</Text>
      <Image source={{ uri: props.photoUrl }} />
    </View>
  );
};

export default class Authentication extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      signedIn: false,
      name: "",
      photoUrl: ""
    };
  }
  signIn = async () => {
    try {
      const result = await Google.logInAsync({
        androidClientId:
          "1056-fpp2cg7r886ln73ri03qqdrvdriek33s.apps.googleusercontent.com",
        iosClientId:
          "106-2n9sl21e06cd36o901f92u3vi07qhd9u.apps.googleusercontent.com",
        scopes: ["profile", "email"]
      });

      if (result.type === "success") {
        this.setState({
          signedIn: true,
          name: result.user.name,
          photoUrl: result.user.photoUrl
        });
      } else {
        console.log("cancelled");
      }
    } catch (e) {
      console.log("error", e);
    }
  };

  render() {
    return (
      <ImageBackground
        source={require("../../assets/images/background.jpg")}
        style={styles.backgroundImage}
      >
        <Header
          centerComponent={{
            text: i18n.t("welcome.title"),
            style: {
              height: 60,
              fontFamily: "FunctionLH",
              fontSize: 30,
              color: "#fff"
            }
          }}
          containerStyle={{
            marginTop: 0,
            backgroundColor: "#6C6363",
            borderBottomColor: "transparent" }}
          statusBarProps={{ barStyle: "light-content" }}
        />
        <View style={styles.container}>
              {this.state.signedIn ? (
              <LoggedInPage
                name={this.state.name}
                photoUrl={this.state.photoUrl}
              />
            ) : (
              <LoginPage signIn={this.signIn} />
            )}
          <Button
            onPress={logIn}
            containerStyle={[styles.mybtnContainer, styles.btnContainerFb]}
            contentStyle={styles.buttonAccueil}
          >
            FACEBOOK
          </Button>
          <Button
            onPress={() => this.props.navigation.navigate("Login")}
            containerStyle={styles.mybtnContainer}
            contentStyle={styles.buttonAccueil}
          >
            {i18n.t("welcome.action.login").toUpperCase()}
          </Button>
            <Button
              onPress={() => this.props.navigation.navigate("Signup")}
              containerStyle={styles.mybtnContainer}
              contentStyle={styles.buttonAccueil}
            >
              {i18n.t("welcome.action.signup").toUpperCase()}
            </Button>
        </View>
      </ImageBackground>
    );
  }
}
...