我正在尝试将 Google 身份验证实现到我的基于 Expo/react 本机组件的类中,但 Expo 给出的示例适用于功能组件。
他们使用此代码进行 Google 身份验证:
import * as React from 'react';
import * as WebBrowser from 'expo-web-browser';
import * as Google from 'expo-auth-session/providers/google';
import { Button } from 'react-native';
WebBrowser.maybeCompleteAuthSession();
export default function App() {
const [request, response, promptAsync] = Google.useAuthRequest({
expoClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
iosClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
androidClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
webClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
});
React.useEffect(() => {
if (response?.type === 'success') {
const { authentication } = response;
}
}, [response]);
return (
<Button
disabled={!request}
title="Login"
onPress={() => {
promptAsync();
}}
/>
);
}
我的问题是我将如何为基于类的组件做类似的事情(
export default class App extends Component
)
要使用 Expo 在基于类的 React Native 组件中实现 Google 身份验证,您需要将功能组件代码调整为类组件。具体方法如下:
步骤:
示例代码:
import React, { Component } from 'react';
import * as WebBrowser from 'expo-web-browser';
import * as Google from 'expo-auth-session/providers/google';
import { Button } from 'react-native';
WebBrowser.maybeCompleteAuthSession();
export default class App extends Component {
constructor(props) {
super(props);
// Initialize state
this.state = {
request: null,
response: null,
promptAsync: null,
};
}
componentDidMount() {
// Initialize Google Auth request
const [request, response, promptAsync] = Google.useAuthRequest({
expoClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
iosClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
androidClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
webClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
});
// Set the request, response, and promptAsync in state
this.setState({ request, response, promptAsync });
}
componentDidUpdate(prevProps, prevState) {
const { response } = this.state;
// Check if the response has changed and if the authentication was successful
if (response?.type === 'success' && prevState.response !== response) {
const { authentication } = response;
// Handle the successful authentication here
}
}
// Method to handle login button press
handleLogin = () => {
const { promptAsync } = this.state;
if (promptAsync) {
promptAsync();
}
};
render() {
const { request } = this.state;
return (
<Button
disabled={!request}
title="Login"
onPress={this.handleLogin}
/>
);
}
}
这实际上是一个通用主题,如何从类组件中调用React的功能组件。
特定于 Google 登录,此答案可以提供帮助:https://stackoverflow.com/a/66974167/1870873