React Native 开发中,为了保持 iOS 和 Android 体验的一致性,原生控件往往无法满足需求。比如系统自带的 Alert 在 Android 上样式比较老旧,难以匹配现代产品的设计规范。这时候就需要我们自定义一个弹窗组件。
核心思路其实很简单,利用 Modal 组件配合 View 和 TouchableOpacity 就能搞定。下面是一个完整的实现方案,你可以直接参考使用。
首先,我们需要定义一个通用的弹窗组件。这里我把它封装成了 CustomAlert,支持标题、内容、确认和取消按钮的自定义。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
StyleSheet,
Text,
View,
Modal,
TouchableOpacity,
Dimensions,
Animated
} from 'react-native';
const { width, height } = Dimensions.get('window');
class CustomAlert extends Component {
static propTypes = {
visible: PropTypes.bool.isRequired,
title: PropTypes.string,
message: PropTypes.string,
confirmText: PropTypes.string,
cancelText: PropTypes.string,
: .,
: .,
};
defaultProps = {
: ,
: ,
: ,
: ,
: {},
: {},
};
() {
{
visible,
title,
message,
confirmText,
cancelText,
onConfirm,
onCancel,
} = .;
(
);
}
}
styles = .({
: {
: ,
: ,
: ,
: ,
},
: {
: width * ,
: ,
: ,
: ,
: ,
},
: {
: ,
: ,
: ,
: ,
},
: {
: ,
: ,
: ,
: ,
},
: {
: ,
: ,
},
: {
: ,
: ,
: ,
},
: {
: ,
},
: {
: ,
},
: {
: ,
},
: {
: ,
},
});
;


