React Native 自定義modal

基於github上的react-native-root-siblings 封裝的一個modal組件,自行npm react-native-root-siblings.

modal組件不再是React Native上的Modal組件, 而是通過react-native-root-siblings 獲取到組件的最外層元素,不需要通過狀態機的方式來隱藏和展示佈局

/**
 *  基於 react-native-root-siblings 封裝的一個modal組件
 *  可自定義View
 *  CustomModal.show(<View />)
 *  CustomModal.hide()
 *
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    TouchableOpacity,
    Dimensions,
    ListView,
    Text,
    Image
} from 'react-native';
import RootSiblings from 'react-native-root-siblings';
var elements = [];
export default class CustomModal extends React.Component {
    static show = (view) => { // 外界傳入view
        let sibling = new RootSiblings(<TouchableOpacity
            style={styles.sibling}
            activeOpacity={1}
            onPress={() => {sibling.destroy()}}
        >
            {view}
        </TouchableOpacity>);
        elements.push(sibling);
    };

   static hide = () => {
        let lastSibling = elements.pop();
        lastSibling && lastSibling.destroy();
    };

}

var styles = StyleSheet.create({
    sibling: {
        height: Dimensions.get('window').height,
        width: Dimensions.get('window').width,
        backgroundColor: '#00000030',
    }
});

使用方法:

import CustomModal from './CustomModal'
//渲染
    render() {
        return (
            <View style={styles.container}
            >
                <TouchableOpacity style={{backgroundColor:'#FFFFFF'}}
                                  onPress={() => CustomModal.show(<CustomView close={() => CustomModal.hide()} />)}
                >
                    <Text>點我</Text>
                </TouchableOpacity>

            </View>
        );
    }

    // 單獨抽出到另一個組件CustomView
    static propTypes = {
        close: PropTypes.func
    };
    render = () => {
        return (
            <View
                activeOpacity={1}
                style={{
                    backgroundColor:"blue", width: 100, height:150,position:'absolute',
                    justifyContent:'center', alignItems:'center', top:64, right:10
                    }}
            >
                <TouchableOpacity onPress={() => this.props.close}>
                    <Text style={{fontSize: 18,color: "#FFFFFF"}}>
                        modal
                    </Text>
                </TouchableOpacity>
            </View>
        )
    }

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章