问题
I am trying to get Google+ login button to work in my React code. The react code is as following (the actual code has proper value for CLIENT_ID).
React.DOM.div({className: "signin-with-google"},
React.DOM.span({id: "signinButton"},
React.DOM.span({
className: "g-signin",
'data-callback': this.signinCallback,
'data-clientid': "CLIENT_ID",
'data-cookiepolicy': "single_host_origin",
'data-scope': "https://www.googleapis.com/auth/userinfo.email"}
)
)
)
The button shows up properly on the page, clicking on it brings up the OAuth dialog and hitting Accept makes it disappear and no errors/warnings are generated either in the dialog or on the javascript console. So to the best of my knowledge everything is working as expected.
However, the callback method this.signinCallback that I am specifying doesn't get invoked. Any, ideas on what I am doing wrong here?
Thanks
回答1:
As stated in the Google+ Sign-in Button docs, data-callback is expected to be "A function in the global namespace". That is because Google's code likely calls your callback by name since all HTML attributes are just strings. It will do something like (warning, not real code):
window[element.dataset["callbackName"]]();
You are passing a reference to your callback, which is not globally accessible. You can expose it when the component is mounted and delete it from the global namespace when it is unmounted:
componentWillMount: function() {
// Somehow generate a unique ID for every G+ button. This uses Underscore's
// `uniqueId` function[1].
//
// [1] http://underscorejs.org/#uniqueId
this.callbackName = _.uniqueId("gPlusCallback-");
window[this.callbackName] = this.signinCallback;
},
componentWillUnmount: function() {
delete window[this.callbackName];
},
render: function() {
...
'data-callback': this.callbackName
...
}
来源:https://stackoverflow.com/questions/26394044/google-signin-button-with-reactjs