React Native Modal組件 Android覆蓋狀態欄

在App開發中常常須要作模態框,咱們第一時間就會想到 React Native 的 Modal 組件,確實Modal組件很方便。但也有一些不盡人意的地方,在安卓App開發的過程當中發現,Modal不會覆蓋狀態欄,就會致使Modal的背景色和狀態欄的顏色不一致,即便是設置了沉浸式狀態欄,這樣破壞了App的總體性和美觀。javascript

Modal組件基本用法

屬性介紹java

  • animationType: ['none', 'slide', 'fade'] Modal展現和收起時的動畫效果
  • onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func 安卓物理返回回調,安卓必傳
  • onShow: func Modal組件展開完成時調用
  • transparent: bool Modal背景色是否透明
  • visible: bool 控制Modal的展開與收起

基本用法react

class ModalDemo extends Component {

    state = {visible: false}
    
    close() {
        this.setState({visible: false})
    }

    render() {
        return (
            <View style={{flex: 1}}> <Modal animationType='slide' transparent visible={this.state.visible} onRequestClose={() => { this.close() }}> <Text>Modal Demo</Text> </Modal> <TouchableOpacity onPress={()=>{this.setState({visible: true})}}> <Text>show</Text> </TouchableOpacity> </View>
        )
    }
}

複製代碼

簡單實現Modal覆蓋狀態欄

其實實現很簡單,在Modal組件外面包一層View,設置View絕對定位,寬高‘100%’,這樣View會佔據整個屏幕,再設置背景,Modal透明就能夠了,這個View的渲染和Modal的visible屬性用同一個state來控制便可。android

{
    this.state.visible ?
        <View style={{position: 'absolute', width: '100%', height: '100%', backgroundColor: 'rgba(0,0,0,0.5)'}}> <Modal animationType='slide' transparent visible={this.state.visible} onRequestClose={() => { this.close() }}> <Text>Modal Demo</Text> </Modal> </View> : null
}
複製代碼

這樣只是實現了覆蓋狀態欄,還須要對各個View層的點擊事件做處理,以致於達到與原始Modal組件相同的效果。ide

基於Modal封裝覆蓋狀態欄的Modal

<TouchableOpacity activeOpacity={1} onPress={() => {this.close()}} style={{ position: 'absolute',width: '100%',zIndex: 999,height: '100%',backgroundColor: 'rgba(0, 0, 0, 0.5)'}}>
    <Modal
        animationType='slide'
        transparent
        visible={this.state.visible}
        onRequestClose={() => { this.close() }}>
        <TouchableOpacity onPress={() => {this.close()}} activeOpacity={1}>
            <TouchableWithoutFeedback onPress={() => {}}>
    				<Text>內容</Text>
            </TouchableWithoutFeedback>
        </TouchableOpacity>
    </Modal>
</TouchableOpacity>
複製代碼

這是我在開發中使用的一種實現方式,原理簡單,實現比較囉嗦。flex

固然也能夠使用大神們的組件,也有大神從安卓底層作了封裝動畫

好比這個:react native modal android實現全屏ui

相關文章
相關標籤/搜索