import { FC, useMemo } from 'react' import { Rate, Space } from 'antd-mobile' import styled, { CSSProperties } from 'styled-components' interface OptionType { id: string name: string } type ValueType = OptionType & { value: number } interface RateValueType { [propName: string]: number } interface RateFieldProps { value?: ValueType[] required: boolean options: OptionType[] allowHalf?: boolean //是否支持半星 style?: any //星星的样式 textStyle?: CSSProperties //尾部文字样式 allowClear?: boolean onChange?: (value: ValueType[]) => void } //状态文字映射 const RATE_MAP: { [propName: number]: string } = { 0: '', 0.5: '非常差', 1: '非常差', 1.5: '差', 2: '差', 2.5: '一般', 3: '一般', 3.5: '好', 4: '好', 4.5: '非常好', 5: '非常好' } const RateField: FC = ({ value = [], options = [], textStyle = { color: 'red' }, onChange, ...other }) => { const rateValues: RateValueType = useMemo(() => { return (value || []).reduce((prv: RateValueType, next) => { prv[next.id || ''] = next.value return prv }, {} as RateValueType) }, [value]) const triggerValue = (changedValue: ValueType[]) => { onChange?.(changedValue) } const onValueChange = (val: number, id: string) => { const newValue: ValueType[] = [...value] const matchValue = newValue.find(item => item.id === id) if (matchValue) { matchValue.value = val } else { const findValue = options.find(item => item.id === id) if (findValue) { newValue.push({ ...findValue, value: val }) } } triggerValue(newValue) } return ( <>
{options.map(option => { return (
{option.name}
onValueChange(val, option.id)} /> {RATE_MAP[rateValues[option.id]]}
) })}
) } const RateItem = styled.div` display: flex; align-items: center; .rate-label { margin-right: 10px; font-size: 14px; } .rate-text { margin-left: 10px; font-size: 14px; } .adm-rate { --star-size: 20px; --inactive-color: #dcdfe4; --active-color: #f48930; } ` export default RateField