|
| 1 | +import React, { useState } from 'react'; |
| 2 | +import shortid from 'shortid'; |
| 3 | + |
| 4 | +import classnames from '../../utils/classNames'; |
| 5 | + |
| 6 | +import './index.scss'; |
| 7 | +import Icon from '../Icons'; |
| 8 | +import { IProps } from './types'; |
| 9 | +import RateIcon from './subcomponents/rate-icon'; |
| 10 | + |
| 11 | +const baseClass = 'vant-rate'; |
| 12 | + |
| 13 | +const renderIcon = ( |
| 14 | + color, |
| 15 | + size, |
| 16 | + icon, |
| 17 | + numberOfIcons, |
| 18 | + handleClick, |
| 19 | + isActive, |
| 20 | + activeCount, |
| 21 | + gutter |
| 22 | +) => { |
| 23 | + const icons = new Array(numberOfIcons); |
| 24 | + for (let i = 0; i < numberOfIcons; i++) { |
| 25 | + icons.push( |
| 26 | + <RateIcon |
| 27 | + index={i} |
| 28 | + gutter={gutter} |
| 29 | + handleClick={(index) => |
| 30 | + handleClick(isActive ? index : index + activeCount) |
| 31 | + } |
| 32 | + key={shortid.generate()} |
| 33 | + icon={<Icon color={color} size={size} name={icon} />} |
| 34 | + className={`${baseClass}__icon`} |
| 35 | + /> |
| 36 | + ); |
| 37 | + } |
| 38 | + return icons; |
| 39 | +}; |
| 40 | + |
| 41 | +const Rate = ({ |
| 42 | + currentRate = 5, |
| 43 | + count = 5, |
| 44 | + size = '20px', |
| 45 | + icon = 'star', |
| 46 | + voidIcon = 'star-o', |
| 47 | + gutter = '4px', |
| 48 | + color = '#ffd21e', |
| 49 | + voidColor = '#c8c9cc', |
| 50 | + disabledColor = '#c8c9cc', |
| 51 | + allowHalf, |
| 52 | + disabled, |
| 53 | + readonly, |
| 54 | + change |
| 55 | +}: IProps) => { |
| 56 | + const [activeCount, setActiveCount] = useState(currentRate || count); |
| 57 | + |
| 58 | + const rateProps = { |
| 59 | + className: classnames(baseClass, [ |
| 60 | + { |
| 61 | + allowHalf, |
| 62 | + disabled, |
| 63 | + readonly |
| 64 | + } |
| 65 | + ]) |
| 66 | + }; |
| 67 | + |
| 68 | + // TODO: Add half star feature |
| 69 | + // TODO: Add touchable feature |
| 70 | + |
| 71 | + const handleClick = (index) => { |
| 72 | + if (!disabled && !readonly) { |
| 73 | + const nextRate = index + 1; |
| 74 | + setActiveCount(nextRate); |
| 75 | + if (!!change) change(nextRate); |
| 76 | + } |
| 77 | + }; |
| 78 | + |
| 79 | + return ( |
| 80 | + <div {...rateProps}> |
| 81 | + {renderIcon( |
| 82 | + disabled ? disabledColor : color, |
| 83 | + size, |
| 84 | + icon, |
| 85 | + activeCount, |
| 86 | + handleClick, |
| 87 | + true, |
| 88 | + activeCount, |
| 89 | + gutter |
| 90 | + )} |
| 91 | + {renderIcon( |
| 92 | + disabled ? disabledColor : voidColor, |
| 93 | + size, |
| 94 | + voidIcon, |
| 95 | + count - activeCount, |
| 96 | + handleClick, |
| 97 | + false, |
| 98 | + activeCount, |
| 99 | + gutter |
| 100 | + )} |
| 101 | + </div> |
| 102 | + ); |
| 103 | +}; |
| 104 | + |
| 105 | +export default Rate; |
0 commit comments