react native 状态栏和安全区域的使用
1. 状态栏组件,react native文档提供了说明。我需要的是设置透明效果,如下图。
代码如下
<StatusBar translucent={true} backgroundColor="rgba(0, 0, 0, 0)" />
解释:StatusBar设置在哪个页面,加载该页面时才会生效。而且作用全局。我们的项目需要,仅仅是透明就可以,我就在登陆界面设置就可以。
2. 安全区域,react native文档提供了safeAreaView,但有问题目前支持IOS,不兼容Android 。我使用了react-navigation里提供的safeAreaView,会导致状态栏透明修过不对。最后采用了第三方库。
react-native-safe-area-view 中它提供的safeAreaView。
最后总的代码
import * as React from 'react'; import { View,Text, StatusBar, Button, StyleSheet,ImageBackground } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; // 导入 SafeAreaProvider ,包裹根组件路由 import { SafeAreaProvider } from 'react-native-safe-area-context'; // 包裹组件 import SafeAreaView from 'react-native-safe-area-view'; function Screen1({ navigation }) { return ( <SafeAreaView style={[styles.container]}> <StatusBar translucent={true} backgroundColor="rgba(0, 0, 0, 0)" /> <ImageBackground style={[styles.imgBackground]} source={require('./img/my_img_bg.png')}> <Text>你好世界</Text> </ImageBackground> <Text style={{color: '#fff'}}>Light Screen</Text> <Button title="Next screen" onPress={() => navigation.navigate('Screen2')} color="#fff" /> </SafeAreaView> ); } function Screen2({ navigation }) { return ( <SafeAreaView style={[styles.container]}> <StatusBar translucent={true} backgroundColor="rgba(0, 0, 0, 0)" /> <ImageBackground style={[styles.imgBackground]} source={require('./img/my_img_bg.png')}> <Text>另一个组件</Text> </ImageBackground> <Button title="Next screen" onPress={() => navigation.navigate('Screen1')} /> </SafeAreaView> ); } const Stack = createStackNavigator(); export default function App() { return ( <SafeAreaProvider> <NavigationContainer> <Stack.Navigator headerMode="none"> <Stack.Screen name="Screen1" component={Screen1} /> <Stack.Screen name="Screen2" component={Screen2} /> </Stack.Navigator> </NavigationContainer> </SafeAreaProvider> ); } const styles = StyleSheet.create({ container: { flex: 1 }, imgBackground:{ flex:0, height: 280, width:"100%", }, });
3. 每个页面,不同的statusBar