2021SC@SDUSC
Rate 评分
- 对评价进行展示。
- 对事物进行快速的评级操作。
API & Methods
属性 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
allowClear | 是否允许再次点击后清除 | boolean | true | |
allowHalf | 是否允许半选 | boolean | false | |
autoFocus | 自动获取焦点 | boolean | false | |
character | 自定义字符 | ReactNode | (RateProps) => ReactNode | <StarFilled /> | function(): 4.4.0 |
className | 自定义样式类名 | string | - | |
count | star 总数 | number | 5 | |
defaultValue | 默认值 | number | 0 | |
disabled | 只读,无法进行交互 | boolean | false | |
style | 自定义样式对象 | CSSProperties | - | |
tooltips | 自定义每项的提示信息 | string[] | - | |
value | 当前数,受控值 | number | - | |
onBlur | 失去焦点时的回调 | function() | - | |
onChange | 选择时的回调 | function(value: number) | - | |
onFocus | 获取焦点时的回调 | function() | - | |
onHoverChange | 鼠标经过时数值变化的回调 | function(value: number) | - | |
onKeyDown | 按键回调 | function(event) | - |
名称 | 描述 |
---|---|
blur() | 移除焦点 |
focus() | 获取焦点 |
部分源码
import * as React from 'react';
import RcRate from 'rc-rate';
import StarFilled from '@ant-design/icons/StarFilled';
import Tooltip from '../tooltip';
import { ConfigContext } from '../config-provider';
引入react rate组件以及antdesign图标中一个可填充星星的图标
export interface RateProps {
prefixCls?: string;
count?: number;
value?: number;
defaultValue?: number;
allowHalf?: boolean;
allowClear?: boolean;
disabled?: boolean;
tooltips?: Array<string>;
onChange?: (value: number) => void;
onHoverChange?: (value: number) => void;
character?: React.ReactNode;
className?: string;
style?: React.CSSProperties;
}
interface RateNodeProps {
index: number;
}
const Rate = React.forwardRef<unknown, RateProps>(({ prefixCls, tooltips, ...props }, ref) => {
const characterRender = (node: React.ReactElement, { index }: RateNodeProps) => {
if (!tooltips) return node;
return <Tooltip title={tooltips[index]}>{node}</Tooltip>;
};
const { getPrefixCls, direction } = React.useContext(ConfigContext);
const ratePrefixCls = getPrefixCls('rate', prefixCls);
return (
<RcRate
ref={ref}
characterRender={characterRender}
{...props}
prefixCls={ratePrefixCls}
direction={direction}
/>
);
});
Rate.displayName = 'Rate';
Rate.defaultProps = {
character: <StarFilled />,
};
export default Rate;
可以看出Rate评分组件的代码量并不多,结构也较为简单,相当于是在rc-rate之上稍作修改
前面是接口,之后是forwardRef函数,最终生成组件Rate
使用
最简单的用法:
import { Rate } from 'antd';
ReactDOM.render(<Rate />, mountNode);
可以使用 (RateProps) => ReactNode
的方式自定义每一个字符。
import { Rate } from 'antd';
import { FrownOutlined, MehOutlined, SmileOutlined } from '@ant-design/icons';
const customIcons = {
1: <FrownOutlined />,
2: <FrownOutlined />,
3: <MehOutlined />,
4: <SmileOutlined />,
5: <SmileOutlined />,
};
ReactDOM.render(
<>
<Rate defaultValue={2} character={({ index }) => index + 1} />
<br />
<Rate defaultValue={3} character={({ index }) => customIcons[index + 1]} />
</>,
mountNode,
);
这样可以达到类似下图的效果