在React Native中将星级添加到Alert组件的方式是通过自定义弹窗组件来实现。以下是实现该功能的步骤:
以下是StarAlert组件的代码示例:
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
const StarAlert = ({ title, description, onConfirm }) => {
const [rating, setRating] = useState(0);
const handleRating = (selectedRating) => {
setRating(selectedRating);
};
const handleConfirm = () => {
onConfirm(rating);
};
return (
<View style={styles.container}>
<Text style={styles.title}>{title}</Text>
<Text style={styles.description}>{description}</Text>
<View style={styles.ratingContainer}>
{[1, 2, 3, 4, 5].map((star) => (
<TouchableOpacity
key={star}
onPress={() => handleRating(star)}
>
<Text
style={[
styles.star,
star <= rating && styles.selectedStar,
]}
>
★
</Text>
</TouchableOpacity>
))}
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={handleConfirm}>
<Text style={styles.confirmButton}>确认</Text>
</TouchableOpacity>
{/* 添加取消按钮的逻辑 */}
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
backgroundColor: '#fff',
padding: 16,
borderRadius: 8,
},
title: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 8,
},
description: {
fontSize: 16,
marginBottom: 16,
},
ratingContainer: {
flexDirection: 'row',
justifyContent: 'center',
marginBottom: 16,
},
star: {
fontSize: 24,
color: '#000',
},
selectedStar: {
color: '#FFD700',
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'flex-end',
},
confirmButton: {
fontSize: 16,
fontWeight: 'bold',
color: '#007BFF',
},
});
export default StarAlert;
在调用StarAlert组件的父组件或页面中,你可以使用以下代码示例来使用该组件并获取用户选择的星级评分:
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import StarAlert from './StarAlert';
const MyComponent = () => {
const handleConfirm = (rating) => {
// 处理用户选择的星级评分
console.log('用户选择的星级评分:', rating);
};
const showStarRating = () => {
StarAlert({
title: '请为我们的应用评分',
description: '请给予您的宝贵评分以帮助我们改进应用。',
onConfirm: handleConfirm,
});
};
return (
<View>
<TouchableOpacity onPress={showStarRating}>
<Text>显示星级评分弹窗</Text>
</TouchableOpacity>
</View>
);
};
export default MyComponent;
这样,在调用showStarRating
方法时,将会弹出一个带有星级评分的弹窗,用户可以点击星星来选择评分。当用户点击确认按钮时,选择的评分将会通过回调函数handleConfirm
传递给父组件或页面进行处理。
领取专属 10元无门槛券
手把手带您无忧上云