import React, {useEffect, useMemo, useState} from 'react'; import {View, Text, StyleSheet, TouchableOpacity} from 'react-native'; import Icon from './icon'; import {$Colors} from './style'; type RatingItemProp = { title: string; level: number; descType?: string[]; onChange?: (data: {title: string; level: number}) => void; onPress?: (i: number) => void; }; const defaultDescType = ['非常满意', '满意', '一般', '较差', '非常差']; const descColor = [$Colors.secondary, $Colors.third, $Colors.fourth, $Colors.fourth, $Colors.fourth]; const stars = [0, 0, 0, 0, 0]; const RatingItem: React.FC = ({level, title, onChange, onPress, descType = defaultDescType}) => { const desc = useMemo(() => descType[5 - level], [level, descType]); const color = useMemo(() => descColor[5 - level], [level]); const handlePress = (starIndex: number) => { onPress && onPress(starIndex + 1); onChange && onChange({level: starIndex + 1, title}); }; return ( {title} {stars.map((star, index) => ( handlePress(index)} activeOpacity={0.9}> index ? color : $Colors.grayII} style={styles.star} /> ))} {desc} ); }; export type RateStateProp = { title: string; level: number; }; export type MakeRattingProps = { Rating: RateStateProp[]; onChange?: (state: RateStateProp[]) => void; isDraft?: boolean; allowExpand?: boolean; }; const MakeRating: React.FC = ({Rating, onChange, isDraft = false, allowExpand = true}) => { const [touched, setTouched] = useState(false); // const calcAverage = (arr: typeof state) => { // return Math.round(arr.reduce((a, i) => a + i.level, 0) / arr.length); // }; const handleUpdate = ({title: selectedTitle, level: newLevel}: RateStateProp) => { let isChange = false; const items = Rating.map((item) => { if (item.title === selectedTitle) { if (item.level !== newLevel) { isChange = true; return {...item, level: newLevel}; } } return item; }); if (isChange) { onChange && onChange(items); } }; const handlePress = (newLevel: number) => { const newRating = Rating.map((rating) => { return {...rating, level: newLevel}; }); onChange && onChange(newRating); allowExpand && setTouched(true); }; useEffect(() => { !allowExpand && setTouched(false); }, [allowExpand]); return ( {!isDraft && !touched ? ( ) : ( Rating.map((item) => ) )} ); }; export default MakeRating; const styles = StyleSheet.create({ wrapper: { display: 'flex', flexDirection: 'column', borderColor: $Colors.grayII, alignItems: 'flex-start', }, ratingItem: { display: 'flex', width: '100%', flexDirection: 'row', alignItems: 'center', paddingTop: 6, paddingBottom: 6, }, ratingTitle: { paddingRight: 10, color: $Colors.normalText, fontSize: 16, }, star: { fontSize: 30, marginLeft: 4, marginRight: 4, }, desc: { textAlign: 'right', fontSize: 14, color: $Colors.lighterText, flex: 1, }, });