React-native 學習之AlertDialog彈出框
阿新 • • 發佈:2019-01-03
/**
* 功能: alert對話方塊
*/
'use strict';
/**
* 匯入模組
*/
// 系統模組
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image,
TouchableHighlight,
Modal,
} from 'react-native';
import PropTypes from 'prop-types';
// 自定義模組
/**
* 匯入樣式
*
*/
// 自定義樣式: 容器樣式、引入列表項樣式
import {Dialog} from '../style/AppStyle';
/**
* 常量
*/
export default class AlertDialog extends Component {
static propTypes = {
title:PropTypes.string.isRequired, // 對話方塊標題
message:PropTypes.string.isRequired, // 對話方塊標題
buttonName: PropTypes.string.isRequired, // 按鈕名字
onClick: PropTypes.func.isRequired, // 回撥函式
};
constructor(props) {
super(props);
// 繫結事件
this._onClick = this._onClick.bind(this); // 需要在回撥函式中使用this,必須使用bind(this)來繫結
}
_onClick() {
if (this.props.onClick) { // 在設定了回撥函式的情況下
this.props.onClick(this.props.pageName); // 執行回撥
}
}
render() {
return (
<Modal
visible={this.props.visibility}
transparent={true}
animationType={'fade'}//none slide fade
onRequestClose={()=>this.setState({visibility:false})}
>
<View style={Dialog.container}>
<View style={Dialog.modalContainer}>
<Text style={Dialog.modalTitle}>{this.props.title}</Text>
<Text style={Dialog.modalMessage}>{this.props.message}</Text>
<View style={Dialog.horizonLine}/>
<View style={Dialog.row}>
<TouchableHighlight style={Dialog.leftBn} onPress={this.props.onClick} >
<Text style={Dialog.leftBnText}>{this.props.buttonName}</Text>
</TouchableHighlight>
</View>
</View>
</View>
</Modal>
)
}
}
樣式:
container:{
flex:1,
backgroundColor:'rgba(0, 0, 0, 0.5)',
justifyContent:'center',
alignItems:'center'
},
modalContainer: {
marginLeft: 50,
marginRight: 50,
borderRadius: 10,
backgroundColor: "white",
alignItems:'center',
},
modalTitle: {
color: '#000000',
fontSize: 16,
marginTop: 10,
},
modalMessage:{
color:'#8a8a8a',
fontSize:14,
margin:10,
},
row:{
flexDirection:'row',
alignItems:'center',
},
horizonLine:{
backgroundColor:'#8a8a8a',
height:0.5,
alignSelf:'stretch'
},
verticalLine:{
backgroundColor:'#9f9fa3',
width:0.4,
alignSelf:'stretch'
},
leftBn:{
borderBottomLeftRadius:3,
padding:7,
flexGrow:1,
justifyContent:'center',
alignItems:'center',
},
leftBnText:{
fontSize:16,
color:'#00A9F2',
},
rightBn:{
borderBottomRightRadius:3,
padding:7,
flexGrow:1,
justifyContent:'center',
alignItems:'center',
},
rightBnText:{
fontSize:16,
color:'#00A9F2'
}
用法
<AlertDialog title="標題" message="訊息" ref="_customModal" visibility={this.state.modalVisibility}
buttonName="確定"
onClick={()=>{
Alert.alert('返回!');
this.setState({modalVisibility:false})
}} />