Implement Facebook API login with reactjs

后端 未结 10 2005
广开言路
广开言路 2020-12-04 09:25

I\'m working on using Facebook\'s Javascript SDK for authentication. I\'ve been able to import the SDK properly and put a Like button on my page. But, the facebook login but

10条回答
  •  孤街浪徒
    2020-12-04 10:10

    This is by far the cleanest and simplest way I could think of if you want to use the button from FB instead of your own.

    To use the button, it's as simple as this.

    
    

    This component is completely self-contained, and highly compostable because it doesn't rely on any external dependency nor does it have any predefined behavior other than rendering the FB login button.

    import React, { Component } from 'react';
    
    class FbLoginBtn extends Component {
      constructor(props) {
        super(props);
    
        // post login behavior should be defined at a higher level
        this.onSuccess = this.props.onSuccess || (() => {});
        this.onFailure = this.props.onFailure || (() => {});
        this.onSuccess = this.onSuccess.bind(this);
        this.onFailure = this.onFailure.bind(this);
      }
    
      componentDidMount() {
        // This is the meat of the component
        // create a script tag, load FB SDK
        // then after script is loaded, set related behavior
        // If you have other components that rely on the FB SDK
        // I recommend extracting this into its own module
        let self = this;
        let scriptTag = document.createElement('script');
        scriptTag.type = 'text/javascript';
        scriptTag.src = "http://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.4&appId=xxxxx";
        scriptTag.addEventListener('load', function (e) {
          self.FB = window.FB;
          // I don't like exposing the SDK to global scope
          window.FB = null;
    
          // This subscribe the callback when login status change
          // Full list of events is here
          // https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v2.9
          self.FB.Event.subscribe('auth.statusChange', self.onStatusChange.bind(self));
        });
        document.body.appendChild(scriptTag);
      }
    
      onStatusChange(response) {
        if (response.status === 'connected') {
          const { accessToken } = response.authResponse;
          // I have a afterLogin optional callback
          // which takes care of ads landing, invitation or any other custom behavior
          this.onSuccess(accessToken, this.props.afterLogin);
        } else {
          this.onFailure();
        }
      }
    
      render() {
        return (
          
    ); } } export default FbLoginBtn;

提交回复
热议问题