很多时候,页面状态栏不同,需要分开设置,iOS设置时需要注意不同机型,安卓则会因为设置不当导致跳转后其他页面的状态栏跟着改变。
参考了这个文献React Native 中的状态栏
后,因为个人能力问题遇到一些坑,做个记录。
1.经过分析,由于功能通用选择写一个高阶组件
import React from 'react'
import hoistNonReactStatics from 'hoist-non-react-statics'
import { StatusBar } from 'react-native'
import { isAndroid } from '../../utils/device'
export const setStatusBar = (statusbarProps = {}) => WrappedComponent => {
class Component extends React.PureComponent {
constructor(props) {
super(props)
this._navListener = props.navigation.addListener('willFocus', this._setStatusBar)
}
componentWillUnmount() {
this._navListener.remove();
}
_setStatusBar = () => {
const {
barStyle = "dark-content",
backgroundColor = '#fff',
translucent = false
} = statusbarProps
StatusBar.setBarStyle(barStyle)
if (isAndroid()) {
StatusBar.setTranslucent(translucent)
StatusBar.setBackgroundColor(backgroundColor);
}
}
render() {
return <WrappedComponent {...this.props} />
}
}
return hoistNonReactStatics(Component, WrappedComponent);
}
高阶组件的使用方法
@setStatusBar({
barStyle: 'light-content',
translucent: true,
backgroundColor: 'transparent'
})
export default class Home extends React.PureComponent {
...
}
适配机型的代码utils/device.js
import { Platform, Dimensions } from 'react-native';
// iPhone X、iPhone XS
const X_WIDTH = 375;
const X_HEIGHT = 812;
// iPhone XR、iPhone XS Max
const XSMAX_WIDTH = 414;
const XSMAX_HEIGHT = 896;
const DEVICE_SIZE = Dimensions.get('window');
const { height: D_HEIGHT, width: D_WIDTH } = DEVICE_SIZE;
export { DEVICE_SIZE };
export const isiOS = () => Platform.OS === 'ios'
export const isAndroid = () => Platform.OS === 'android'
export const isiPhoneX = () => {
return (
isiOS() &&
((D_HEIGHT === X_HEIGHT && D_WIDTH === X_WIDTH) ||
(D_HEIGHT === X_WIDTH && D_WIDTH === X_HEIGHT)) ||
((D_HEIGHT === XSMAX_HEIGHT && D_WIDTH === XSMAX_WIDTH) ||
(D_HEIGHT === XSMAX_WIDTH && D_WIDTH === XSMAX_HEIGHT))
);
};
export const ifiPhoneX = (iPhoneXStyle, regularStyle) => isiPhoneX() ? iPhoneXStyle : regularStyle
完美,然而,安卓手机上详情页返回首页的时候页面不刷新,首页状态栏变的和详情页一样了。。。
这是只需要去详情页的componentWillUnmount里设置一下StatusBar
componentWillUnmount() {
StatusBar.setBarStyle('light-content');
StatusBar.setBackgroundColor('#ecf0f1');
}
不过在componentWillUnmount里面设置,返回之后状态栏改变有点延迟,所以我把设置写在返回按钮的点击事件里了
onPress={()=>{
StatusBar.setBarStyle('light-content');
StatusBar.setBackgroundColor('#ecf0f1');
NavigationUtil.goBack(this.props.navigation);
}}>
OK,这时候就可以了
有什么问题欢迎指正。
网友评论