一、 如何让自定义对话框(Modal)点击屏幕空白消失
Modal使用这里不做解释了。要让用户点击屏幕空白处就能让对话框消失,这里用到了RN提供的 TouchableWithoutFeedback 组件。
该组件有两个坑,使用时要注意:
- 该组件包裹的子元素有且只能有一个,类似于 ScrollView
- 该组件设置style无效。所以得要把style设置到子组件里
下面列出点击空白处对话框消失的例子:
LogoutDialog.js1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54export default class LogoutDialog extends Component{
render(){
let {show, closeDialog, changeAccount, exitApp} = this.props
return(
<Modal animationType='none'
transparent={true}
visible={show}
onRequestClose={closeDialog}
onShow={this.startShow}>
<TouchableWithoutFeedback onPress={closeDialog}>
<View style={styles.rootStyle}>
<View style={styles.modalContainer}>
<ImageLabel leftIcon={require('../resources/ic_logout_change_acc.png')}
rightLabel='切换账号'
labelStyle={{fontSize: 20, marginLeft: '10%'}}
clickAction={changeAccount}
/>
<View style={{width:'100%', height:1, backgroundColor:'#F4F4F4'}}/>
<ImageLabel leftIcon={require('../resources/ic_logout_exit.png')}
rightLabel='关闭应用'
labelStyle={{fontSize: 20, marginLeft: '10%'}}
clickAction={exitApp}
/>
</View>
</View>
</TouchableWithoutFeedback>
</Modal>
)
}
}
const styles = StyleSheet.create({
rootStyle:{
flexDirection:'column',
flex:1,
alignItems:'center',
justifyContent:'center',
backgroundColor:'rgba(0, 0, 0, 0.5)'
},
modalContainer:{
width:'60%',
backgroundColor:'white',
borderRadius:10,
alignItems: 'center'
}
})
ImageLabel.js代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14export default class ImageLabel extends Component{
render() {
let {leftIcon, rightLabel, labelStyle, clickAction} = this.props;
return(
<TouchableOpacity style={[RowStyle.rowDialog, {height: 80}]} onPress={clickAction}>
<Image source={leftIcon} />
<Text style={labelStyle}>{rightLabel}</Text>
</TouchableOpacity>
)
}
}
二、Modal有一个属性: transparent, 若不设置其为true也就是透明,会看不到底部被遮盖的控件。