[RN] reactnavigation配合StatusBar設定狀態列
阿新 • • 發佈:2018-11-09
本文將為大家介紹使用reactnavigation時如何配合使用StatusBar來設定和更改狀態列樣式。
本文只介紹tabnavigation的情況即2.x版本中使用createBottomTabNavigator建立的Tab導航。其它的情況在reactnavigation官網有詳細的介紹,大家可以直接去看官方介紹:Different status bar configuration based on route。
先看效果:
reactnavigation官網說的也很明確,Tabnavigation的情況比較特殊,在切換Tab時,StatusBar屬性是全域性更改的,即Tab1設定了狀態列樣式為A,Tab2設定狀態列樣式為B,當點選Tab1時,Tab2的狀態列樣式也會被全域性的設定為A,相信大家嘗試過的人已經深有體會了。
官方提供的方法是在螢幕渲染時動態的修改當前頁面的StatusBar狀態。
看程式碼:
class Screen1 extends React.Component { componentDidMount() { this._navListener = this.props.navigation.addListener('didFocus', () => { StatusBar.setBarStyle('light-content'); isAndroid && StatusBar.setBackgroundColor('#6a51ae'); }); } componentWillUnmount() { this._navListener.remove(); } ... } class Screen2 extends React.Component { componentDidMount() { this._navListener = this.props.navigation.addListener('didFocus', () => { StatusBar.setBarStyle('dark-content'); isAndroid && StatusBar.setBackgroundColor('#ecf0f1'); }); } componentWillUnmount() { this._navListener.remove(); } ... }