为什么在单击按钮时不触发回调?

时间:2019-06-27 11:56:45

标签: reactjs facebook-login

我正在使用名为react-facebook-login的react npm创建一个登录按钮。问题是按钮组件的回调不返回任何内容。

这是我在其中创建按钮的按钮组件

import React, {Component} from 'react';
import FacebookLogin from 'react-facebook-login'

export default class Facebook extends Component {


    state = {
        isLoggedin: false,
        userID: '',
        name: '',
        email: '',
        picture: ''
    }

    responseFacebook = response => {
        console.log(response);
    }

    componentClicked = () => console.log("clicked");


    render() {
        let fbContent;

        if(this.state.isLoggedin){
            fbContent =null;
        }
        else {
          console.log("test");
          fbContent = (
          <FacebookLogin
          appId="xxxxxxx"
          autoLoad={true}
          fields="name,email,picture"
          onClick={this.componentClicked}
          callback={this.responseFacebook} />)  
        }


        return <div>{fbContent}</div>

    }


}

onClick事件起作用,回调不起作用。

*请注意,我已经在代码中检查了appId的正确性。

1 个答案:

答案 0 :(得分:0)

这应该是使用功能组件时的代码,

import React from 'react';
import ReactDOM from 'react-dom';
import FacebookLogin from 'react-facebook-login';

const responseFacebook = (response) => {
  console.log(response);
}

const componentClicked = () => console.log("clicked");

ReactDOM.render(
  <FacebookLogin
    appId="xxxxxxxxxx"
    autoLoad={true}
    fields="name,email,picture"
    onClick={componentClicked}
    callback={responseFacebook} />,
  document.getElementById('demo')
);

使用类组件时

import React from 'react';
import FacebookLogin from 'react-facebook-login';

class MyComponent extends React.Component {
  responseFacebook(response) {
    console.log(response)
  }

  componentClicked(){
     console.log("clicked");
  }

  render() {
    return (
      <FacebookLogin
        appId="1088597931155576"
        autoLoad={true}
        fields="name,email,picture"
        onClick={componentClicked}
        callback={this.responseFacebook}
      />
    )
  }
}

export default MyComponent;

Ref

也请检查此内容-Permissions Reference - Facebook Login

更新

不要这样做

export default class Facebook extends Component {...} //dont export your component on same line

相反,您应该这样做

class Facebook extends Component {...}

export default Facebook