feat: rating allow clear (#2017)

This commit is contained in:
zhangchen 2021-05-25 17:28:36 +08:00 committed by GitHub
parent 7993bf61ff
commit 66c53436a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 4 deletions

View File

@ -33,3 +33,4 @@ order: 37
| half | `boolean` | `false` | 是否使用半星选择 |
| count | `number` | `5` | 共有多少星可供选择 |
| readOnly | `boolean` | `false` | 只读 |
| allowClear | `boolean` | `true` | 是否允许再次点击后清除 |

View File

@ -23,6 +23,7 @@ interface RatingProps {
readOnly: boolean;
classPrefix: string;
disabled?: boolean;
allowClear?: boolean;
classnames: ClassNamesFn;
}
@ -31,6 +32,7 @@ export class Rating extends React.Component<RatingProps, any> {
containerClass: 'rating',
readOnly: false,
half: true,
allowClear: true,
value: 0,
count: 5,
char: '★',
@ -43,6 +45,7 @@ export class Rating extends React.Component<RatingProps, any> {
this.state = {
value: props.value || 0,
stars: [],
isClear: false,
halfStar: {
at: Math.floor(props.value),
hidden: props.half && props.value % 1 < 0.5
@ -102,6 +105,8 @@ export class Rating extends React.Component<RatingProps, any> {
}
mouseOver(event: React.ChangeEvent<any>) {
const {isClear} = this.state;
if (isClear) return;
let {readOnly, size, half} = this.props;
if (readOnly) return;
let index = Number(event.target.getAttribute('data-index'));
@ -130,9 +135,10 @@ export class Rating extends React.Component<RatingProps, any> {
}
mouseLeave() {
let {value} = this.state;
const {value, isClear} = this.state;
const {half, readOnly} = this.props;
if (readOnly) return;
if (isClear) return this.setState({isClear: false});
if (half) {
this.setState({
halfStar: {
@ -147,9 +153,10 @@ export class Rating extends React.Component<RatingProps, any> {
}
handleClick(event: React.ChangeEvent<any>) {
const {half, readOnly, onChange, size} = this.props;
const {half, readOnly, onChange, size, allowClear} = this.props;
if (readOnly) return;
let index = Number(event.target.getAttribute('data-index'));
let value;
if (half) {
const isAtHalf = this.moreThanHalf(event, size);
@ -164,9 +171,11 @@ export class Rating extends React.Component<RatingProps, any> {
} else {
value = index = index + 1;
}
const isClear = allowClear && value === this.state.value;
if (isClear) value = index = 0;
this.setState({
value: value,
stars: this.getStars(index)
value, stars: this.getStars(index), isClear
});
onChange && onChange(value);
}