react-native 获取设备信息 和 常见监听API

2023-11-21  本文已影响0人  暴躁程序员

一、获取设备的系统、版本号、窗口宽高、像素比、字体缩放比

1. 获取设备的系统和版本号(Platform)
import React from 'react';
import {Platform, Text, View} from 'react-native';

const App = () => {
  return (
    <View>
      <Text>当前设备是android还是ios系统:{Platform.OS}</Text>
      <Text>
        系统版本:
        {Platform.OS === 'android'
          ? Platform.Version
          : parseInt(Platform.Version, 10)}
      </Text>
      <Text>isTV:{Platform.isTV.toString()}</Text>
      {Platform.OS === 'ios' && (
        <>
          <Text>isPad:{Platform.isPad.toString()}</Text>
        </>
      )}
      <Text>其他 Constants:{JSON.stringify(Platform.constants, null, 2)}</Text>
    </View>
  );
};
export default App;
2. 实时获取设备窗口宽高、屏幕宽高、像素比、字体缩放比(Dimensions)
import React, {useState, useEffect} from 'react';
import {View, Text, Dimensions} from 'react-native';

const initWindow = Dimensions.get('window');
const initScreen = Dimensions.get('screen');

const App = () => {
  const [dimensions, setDimensions] = useState({
    window: initWindow,
    screen: initScreen,
  });

  const onChange = ({window, screen}) => {
    setDimensions({window, screen});
  };

  useEffect(() => {
    Dimensions.addEventListener('change', onChange);
    return () => {
      Dimensions.removeEventListener('change', onChange);
    };
  });

  return (
    <View>
      <Text>窗口高度:{dimensions.window.height}</Text>
      <Text>窗口宽度:{dimensions.window.width}</Text>
      <Text>设备像素比:{dimensions.window.scale}</Text>
      <Text>字体缩放比:{dimensions.window.fontScale}</Text>
      <Text>屏幕高度(更高):{dimensions.screen.height}</Text>
      <Text>屏幕宽度:{dimensions.screen.width}</Text>
    </View>
  );
};

export default App;
3. 获取设备像素比和文字缩放比
import React from 'react';
import {PixelRatio, Text, View} from 'react-native';

function App() {
  return (
    <View>
      <Text>设备像素比:{PixelRatio.get()}</Text>
      <Text>文字缩放比:{PixelRatio.getFontScale()}</Text>
      <Text>将dp转化为px:{PixelRatio.getPixelSizeForLayoutSize(100)}</Text>
    </View>
  );
}
export default App;

二、监听程序是否处于前台、系统键盘显示隐藏、返回键监听、退出当前程序

1.监听当前程序处于前台还是后台运行(AppState)
import React, {useRef, useState, useEffect} from 'react';
import {AppState, Text, View} from 'react-native';

const AppStateExample = () => {
  const appState = useRef(AppState.currentState);
  const [appStateVisible, setAppStateVisible] = useState(appState.current);

  useEffect(() => {
    const subscription = AppState.addEventListener('change', nextAppState => {
      // 在此可判断程序是否进入前台
      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === 'active'
      ) {
        console.log('App 已进入前台');
      }

      // 获取并渲染进入前台的状态
      appState.current = nextAppState;
      setAppStateVisible(appState.current);
      console.log('AppState', appState.current);
    });

    return () => {
      subscription.remove();
    };
  }, []);

  return (
    <View>
      <Text>当前程序处于: {appStateVisible}</Text>
    </View>
  );
};

export default AppStateExample;
2. 监听系统键盘的显示和隐藏
import React, {useEffect} from 'react';
import {Keyboard, TextInput} from 'react-native';

const Example = () => {
  useEffect(() => {
    Keyboard.addListener('keyboardDidShow', _keyboardDidShow);
    Keyboard.addListener('keyboardDidHide', _keyboardDidHide);

    // 移除监听
    return () => {
      Keyboard.removeListener('keyboardDidShow', _keyboardDidShow);
      Keyboard.removeListener('keyboardDidHide', _keyboardDidHide);
    };
  }, []);

  const _keyboardDidShow = () => {
    alert('显示键盘');
  };

  const _keyboardDidHide = () => {
    alert('隐藏键盘');
  };

  return (
    <TextInput
      placeholder="Click here ..."
      onSubmitEditing={Keyboard.dismiss}
    />
  );
};
export default Example;
3. 返回键监听,退出当前程序(仅 Android)
import React, {useEffect} from 'react';
import {Text, View, BackHandler, Alert} from 'react-native';

const App = () => {
  useEffect(() => {
    // 1. 返回键监听
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      () => {
        Alert.alert('提示', '你确定要要退出当前程序吗?', [
          {
            text: '取消',
            onPress: () => null,
            style: 'cancel',
          },
          {text: '确认', onPress: () => BackHandler.exitApp()}, // 2. 退出当前程序
        ]);
        return true;
      },
    );

    return () => backHandler.remove();
  }, []);

  return (
    <View>
      <Text>返回键监听 + 退出当前程序</Text>
    </View>
  );
};

export default App;
上一篇下一篇

猜你喜欢

热点阅读