基于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>
)
}