React Native项目中实现锁住手机屏幕功能

资讯 2年前 (2022) 千度导航
36 0 0

设置PinCode锁住屏幕时是很常见的场景,下面教程是使用react-native-pincode开源组件来实现react-native锁住手机屏幕的功能。

该组件官方地址:

https://github.com/jarden-digital/react-native-pincode

  1. 安装:
yarn add @haskkor/react-native-pincode @react-native-community/async-storage react-native-keychain@5.0.1

2. 因为组件使用了系统提供的VIBRATE,所以在
android/app/src/main/AndroidManifest.xml文件夹添加权限:

<uses-permission android:name="android.permission.VIBRATE"/>

3.使用:

import React, {useCallback, useEffect, useState} from 'react';
import {View, StyleSheet} from 'react-native';
import {RouterStackScreenProps} from '../../types/types';
import PINCode, {hasUserSetPinCode} from '@haskkor/react-native-pincode';
import {setShowPinLock} from '../../redux/reducers/userReducer';
import {useAppDispatch} from '../../hooks/redux-hooks';

type LoginScreenProps = RouterStackScreenProps<'LoginScreen'>;

const LoginScreen = ({route, navigation}: LoginScreenProps) => {
  const dispatch = useAppDispatch();

  const [pinCodeStatus, setPinCodeStatus] = useState<boolean>(false);

  const hasPin = useCallback(async () => {
    const data = await hasUserSetPinCode();
    setPinCodeStatus(data);
  }, []);

  useEffect(() => {
    hasPin().catch(console.error);
  }, [hasPin]);

  console.log('hasPin:', hasPin());

  return (
    <View style={styles.container}>
      <PINCode
        status={!pinCodeStatus ? 'choose' : 'enter'}
        touchIDDisabled={true}
        finishProcess={() => {
          dispatch(setShowPinLock(false));
          navigation.navigate('TabNavigator', {
            screen: 'HomeScreen',
          });
        }}
      />
    </View>
  );
};

export default LoginScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
});

代码说明:

  • PINCode组件的status传的参数,如果是choose表示第一次设置pincode,需要用户输入和确认pincode,如果是enter表示之前已经设置过pincode。每次进入页面,使用useEffect调用组件提供的hasUserSetPinCode来判断是否已经设置过pincode,从而动态传入status参数
  • finishProcess是组件成功输入pincode后回调函数,使用react-navigation提供navigate跳转到tab底部栏的home页面。因为我使用了redux中的showPinLock变量来做动态路由判断,这时还需要更改showPinLock变量的值(这点要根据实际项目需求灵活调整,可有可无)
版权声明:千度导航 发表于 2022年9月10日 11:56。
转载请注明:React Native项目中实现锁住手机屏幕功能 | 千度百科

相关文章