如何在官方反应原生模态上添加背景可点击的叠加层?



这是官方的 react-native 模态文档,这是 iOS 和 Android 的一个实时示例。

如何添加位于我的视图和模态下方的可点击背景叠加层?

您可以将模态内容包装在可触摸的不透明度中,并使用背景设置其样式。我编辑了文档中给出的示例。

<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<TouchableOpacity
style={{ backgroundColor: 'black', flex: 1,justifyContent:'center' }}
onPress={() => setModalVisible(!modalVisible)}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Hello World!</Text>
<TouchableHighlight
style={{ ...styles.openButton, backgroundColor: '#2196F3' }}
onPress={() => {
setModalVisible(!modalVisible);
}}>
<Text style={styles.textStyle}>Hide Modal</Text>
</TouchableHighlight>
</View>
</TouchableOpacity>
</Modal>

React Native Elements 有一个很棒的组件叫做Overlay可以解决你的问题。本周早些时候它救了我。唯一的问题是它是一个更大的库的一部分。
https://react-native-elements.github.io/react-native-elements/docs/overlay.html

我认为如果背景和模态之间的分离对您的项目不重要,您可以这样处理它:

<Modal
animationType="slide"
transparent={true}
style={{ width: '100%', alignSelf: 'center', height: '100%', justifyContent: 'flex-start' }}
visible={this.state.modalVisible}
onRequestClose={() => {
// Do smth
}}>
<TouchableWithoutFeedback style={{ flex: 1 }} onPress={() => {
// Do the backdrop action
}}>
<View style={{ backgroundColor: '#fff', flex: 1, width: '80%', height: '50%' }} >
<Text> Your content </Text>
</View>
</TouchableWithoutFeedback>
</Modal>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
// Touchable Opacity
<TouchableOpacity
style={{ position: 'absolute' , flex: 1 }}
onPress={() => setModalVisible(!modalVisible)} />
<View style={styles.modalView}>
// Other..
<View>
design
</View>
</Modal>

最新更新