React native自定义Model

Modal 组件是一种简单的覆盖在其他视图之上显示内容的方式。类似于Android端的Dialog,PopuWindow

常用属性 Props
  • visible: {true|false} 控制Model是否显示。
  • animationType :{"slide"|"fade"|"none"} ,Model动画。slide 从底部滑入滑出;fade 淡入淡出;none 没有动画,直接蹦出来。默认是none。
  • onShow: 回调函数会在 modal 显示时调用。
  • onDismiss:回调会在 modal 被关闭时调用。
简单自定义Model组件

MyModel.js

import React from "react";
import {
    StyleSheet, Text, Modal, TouchableWithoutFeedback, TouchableHighlight, View,
    Dimensions, Button
} from "react-native";

const screenLayout = Dimensions.get("window");
const screenWidth = screenLayout.width;
const screenHeight = screenWidth.height;

export default class MyModel extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            modalVisible: false,
        }
    }
    render() {
        return (<Modal
            animationType={"fade"}
            transparent={true}
            onRequestClose={() => { }}
            visible={this.state.modalVisible}>
            <TouchableHighlight
                style={{ flex: 1 }}
                onPress = {() =>{
                 //点击空白处消失
                  this.closeDialog()
                }}
                underlayColor='transparent'>
                
                <View style={styles.backgroundContainer} >
                    <View style = {{width:200,height:200,backgroundColor:"white",
                     justifyContent:'center',alignItems:'center'}} >
                    <Text>自定义Model</Text>
                    </View>
                </View>
            </TouchableHighlight>
        </Modal>)
    }
    openDialog = () => {
        this.setState({
            modalVisible: true,
        })
    }
    closeDialog = () => {
        this.setState({
            modalVisible: false,
        })
    }
}
const styles = StyleSheet.create({
    backgroundContainer: {
        flex:1,
        height: screenHeight,
        width: screenWidth,
        backgroundColor: 'rgba(0,0,0,0.5)',
        alignItems: "center",
        flexDirection:'row',
        justifyContent:'center'
    },
})

在需要弹出显示的地方导入组件

import MyModel from './model/MyModel';

....
 render() {
    const { navigation } = this.props;
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <View style={{ marginTop: 20 }}>
          <Button
            onPress={() => {
              this.refs.myModel.openDialog()
            }}
            title="弹出一个Model" />
        </View>
       <MyModel ref={'myModel'}/>
      </View>
    );
  }
20190731_175512.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。