Created
January 31, 2019 09:58
-
-
Save shrekuu/0f14a5462e24fdcbe0a0fbbeb2b27c0f to your computer and use it in GitHub Desktop.
react-native 微信登录示例代码片段
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Sample React Native App | |
* https://github.com/facebook/react-native | |
* | |
* @format | |
* @flow | |
* @lint-ignore-every XPLATJSCOPYRIGHT1 | |
*/ | |
import React, {Component} from 'react'; | |
import {Platform, StyleSheet, Text, View, Alert } from 'react-native'; | |
import * as WeChat from 'react-native-wechat' | |
import { from, of } from 'rxjs' | |
import { switchMap, map } from 'rxjs/operators' | |
const instructions = Platform.select({ | |
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', | |
android: | |
'Double tap R on your keyboard to reload,\n' + | |
'Shake or press menu button for dev menu', | |
}); | |
type Props = {}; | |
export default class App extends Component<Props> { | |
componentDidMount () { | |
// 注册, todo: 这里从微信那申请来的填写 appid | |
from(WeChat.registerApp('xxx')) | |
.pipe( | |
switchMap(() => from(WeChat.isWXAppInstalled())), | |
map(installed => { | |
if (!installed) { | |
console.log('是否安装着微信: ', installed) | |
throw Error('未安装微信') | |
} | |
}), | |
// 授权 | |
switchMap(() => from(WeChat.sendAuthRequest('snsapi_userinfo'))), | |
// 拿到 code, 去后台登录 | |
switchMap((payload) => { | |
return of(payload) | |
}), | |
).subscribe( | |
res => { | |
console.log('res', res) | |
// todo: 登录成功, 存起来 | |
}, | |
err => { | |
console.log('err', err.message) | |
// 出错, 提示用户 | |
Alert.alert(err.message) | |
}, | |
) | |
} | |
render() { | |
return ( | |
<View style={styles.container}> | |
<Text style={styles.welcome}>Welcome to React Native!</Text> | |
<Text style={styles.instructions}>To get started, edit App.js</Text> | |
<Text style={styles.instructions}>{instructions}</Text> | |
</View> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
justifyContent: 'center', | |
alignItems: 'center', | |
backgroundColor: '#F5FCFF', | |
}, | |
welcome: { | |
fontSize: 20, | |
textAlign: 'center', | |
margin: 10, | |
}, | |
instructions: { | |
textAlign: 'center', | |
color: '#333333', | |
marginBottom: 5, | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment