如何在不使用弹出窗口的情况下使用React Native和Firebase登录到Google?

时间:2019-11-17 01:34:56

标签: javascript firebase react-native firebase-authentication

正如我所说,我想登录到我的Google帐户而不必创建一个弹出窗口,我的意思是将登录表单与这些输入内容保持在一起,以免模拟器上的屏幕空白。 (很抱歉,图像看起来像这样,我不知道如何在此处进行编辑。)enter image description here

我将复制并粘贴Firebase登录代码:

  onButtonPress() {
    const {email, password} = this.state;

    this.setState({ error: '', loading: true });

    firebase.auth().signInWithEmailAndPassword(email, password)
    .then(this.onLoginSuccess.bind(this))
    .catch(() => {
      firebase.auth().createUserWithEmailAndPassword(email, password)
        .then(this.onLoginSuccess.bind(this))
        .catch(this.onLoginFail.bind(this));
  })
}

但是目前,它是使用电子邮件和密码登录的,而不是google。

我正在尝试获取用户名,所以这就是为什么我要使用google登录。

1 个答案:

答案 0 :(得分:0)

这是我对Google身份验证所做的一个React部分。它不是为您的代码量身定做的,但我认为它可能会帮助您到达想要的地方!

class GoogleAuth extends React.Component {
  componentDidMount() {
    window.gapi.load("client:auth2", () => {
      window.gapi.client
        .init({
          clientId:
            "65397550643-g040rl648ka1p4d0h0t58crsa5v8ni1a.apps.googleusercontent.com",
          scope: "email"
        })
        .then(() => {
          this.auth = window.gapi.auth2.getAuthInstance();
          this.onAuthChange(this.auth.isSignedIn.get());
          this.auth.isSignedIn.listen(this.onAuthChange);
        });
    });
  }

  onAuthChange = isSignedIn => {
    if (isSignedIn) {
      this.props.signIn(this.auth.currentUser.get().getId());
    } else {
      this.props.signOut();
    }
  };

  onSignInClick = () => {
    this.auth.signIn();
  };

  onSignOutClick = () => {
    this.auth.signOut();
  };

  renderAuthButton = () => {
    if (this.props.isSignedIn === null) {
      return null;
    } else if (this.props.isSignedIn) {
      return (
        <button className="ui red google button" onClick={this.onSignOutClick}>
          <i className="google icon" />
          Sign Out
        </button>
      );
    } else {
      return (
        <button className="ui green google button" onClick={this.onSignInClick}>
          <i className="google icon" />
          Sign in with Google
        </button>
      );
    }
  };

  render() {
    return <div className="item">{this.renderAuthButton()}</div>;
  }
}