ReactNative对话框的实现
ReactNative官方的Modal在使用了预加载JS和RootView优化功能之后,就不能弹Modal窗口,而Modal窗口弹出来的前提是需要当前的Context上下文,而预加载初始化的相关工作传入的context要么是application或其它activity的上下文。
在这种情况下,我们需要实现弹窗效果就需要其它方案来解决,那么这里就是解决方案;
一、ReactNaitve JavaScript实现Dialog源码
'use strict'
import React, {Component} from 'react';
import {
StyleSheet,
View,
StatusBar,
Dimensions, TouchableWithoutFeedback
} from 'react-native';
const {width, height} = Dimensions.get('window');
const [left, top] = [0, 0];
export default class Dialog extends React.Component {
constructor(props) {
super(props);
this.state = {
isHidden: this.props.isHidden
};
this.position = this.props.position || "center";
this.outSideDisappear = this.props.outSideDisappear || true;
this.height = this.props.height || 0;
this.contentStyle = this.props.contentStyle;
this.margin = this.props.margin || 0;
}
/**
* 隐藏对话框
*/
dismiss = () => {
this.setState({
isHidden: true
});
}
/**
* 显示对话框
*/
show = () => {
this.setState({
isHidden: false
});
}
/**
* 点击透明区域是否消失对话框;
*/
onDialogOutSideClicked = () => {
if (this.props.outSideDisappear) {
this.dismiss();
}
}
render() {
//计算屏的高度
let screenHeight = height - StatusBar.currentHeight;
//计算对话框内容区域top的起点位置;
let top = this.position == "center" ? (screenHeight - this.height) / 2
: this.position == "top" ? this.margin
:(screenHeight - this.height - this.margin ) ;
return this.state.isHidden ? : (
{
//对话框半透明背景
}
{
//对话内容区域视图渲染
}
{this.props.children}
);
}
}
const styles = StyleSheet.create({
dialog_container: {
position: "absolute",
width: width,
height: height,
left: left,
top: top,
},
dialog_mask: {
justifyContent: "center",
backgroundColor: "#383838",
opacity: 0.8,
position: "absolute",
width: width,
height: height,
left: left,
top: top,
},
dialog_center: {
position: "absolute",
width: width,
backgroundColor: "#FFFFFF",
justifyContent: "center",
alignSelf: "center",
left: left,
}
});
二、Dialog的使用说明
导入Dialog.js文件后,在你的界面render方法中加入如下代码.
Dialog定义了如下基本属性
...
const styles = StyleSheet.create({
dialog : {
justifyContent:"flex-start",
backgroundColor: "#ffffff",
borderRadius:5,
},
title:{
color:"#000000",
alignSelf:"center",
fontSize:18,
height:25,
marginTop:10,},
content:{
color:"#000000",
alignSelf:"flex-start",
height:70,
fontSize:17,
marginLeft:50,
textAlignVertical:"center"},
cancel:{
color:"#000000",
alignSelf:"center",
fontSize:18,
height:25,
marginTop:10,
marginRight:50},
ok:{
color:"#000000",
alignSelf:"center",
fontSize:18,
height:25,
marginTop:10,
marginLeft:50},
dialogContent:{
flexDirection:"row",
justifyContent:"center",
alignItems:"center"}
});
效果图如下
image.png