ReactNative: 使用模态组件Modal组件

一、简介

在iOS端切换控制器的方式大致有三种,分别是导航、标签、模态,在ReactNative中也有这三种方式可以实现。在前面的文章中已经实现了用导航和标签切换页面,同样地,RN中也有一个模态组件Modal组件来进行页面的切换。

二、API

Modal组件提供的属性不多,但是都比较常用,现在来分析一下每一个属性用法,如下所示:

//模态的动画过渡方式 
//none: 无效果
//slide:滑动效果
//fade:渐入渐出效果
animationType: PropTypes.oneOf(['none', 'slide', 'fade']),

//确定您的模态是否会填充整个视图。 将其设置为“ true”将在透明背景上渲染模态。
transparent: PropTypes.bool

//控制是否对底层窗口强制进行硬件加速
hardwareAccelerated: PropTypes.bool

//模态的页面是否可见
visible: PropTypes.bool

//当用户点击硬件后退按钮时,将调用onRequestClose回调。区分平台使用
onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func

//模态页面显示时调用
onShow: PropTypes.func

//模态的动画过渡方式 , 已过时,被属性animationType取代
animated: deprecatedPropType(
      PropTypes.bool,
      'Use the `animationType` prop instead.'
    )

//支持的屏幕旋转方向
supportedOrientations: PropTypes.arrayOf(PropTypes.oneOf(['portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right']))

//当屏幕旋转时调用
onOrientationChange: PropTypes.func

三、使用

可以看出API比较简单,现在简单实现一下,注意Modal组件内部需要嵌套一个页面View,示例如下:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';

import {
    AppRegistry,
    StyleSheet,
    View,
    Text,
    TouchableHighlight,
    Modal
} from 'react-native';


export default class ReactNativeDemo extends Component {

    //默认模态视图不可见
    state = {
      modalVisible: false,
    };

    //修改模态视图可见性
    setModalVisible(visible) {
        this.setState({modalVisible: visible});
    }

    render() {
        return (
            <View style={[styles.flex,styles.show_bgColor,styles.center]}>
                <Modal
                    animationType={"slide"}
                    transparent={false}
                    visible={this.state.modalVisible} >
                    
                    <View style={[styles.flex,styles.hide_bgColor,styles.center]}>
                        <View>
                            <TouchableHighlight onPress={() => { this.setModalVisible(!this.state.modalVisible)}}>
                                <Text style={{fontSize:20,color:'white'}}>Hide Modal</Text>
                            </TouchableHighlight>
                         </View>
                    </View>
                </Modal>

                <TouchableHighlight onPress={() => { this.setModalVisible(true) }}>
                    <Text style={{fontSize:20,color:'white'}}>Show Modal</Text>
                </TouchableHighlight>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    flex: {
        flex: 1
    },
    show_bgColor: {
      backgroundColor: 'green'
    },
    hide_bgColor: {
        backgroundColor: 'red'
    },
    center: {
        alignItems: 'center',
        justifyContent: 'center',
    }
});

AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);

猜你喜欢

转载自www.cnblogs.com/XYQ-208910/p/12145893.html