@uiw/react-native
Version:
UIW for React Native
77 lines (72 loc) • 2.06 kB
JavaScript
import React from 'react';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
import Icon from '../Icon';
export default class Rating extends React.Component {
constructor(props) {
super(props);
let start = props.icon && props.icon[0] || 'star-off';
let end = props.icon && props.icon[1] || 'star-on';
this.state = {
defaultRating: props.defaultRating || 0,
resultRating: props.resultRating || 5,
icon: [],
size: props.size ?? 24,
color: props.color || '#ebc445',
typeIcon: [start, end]
};
}
componentDidMount() {
const {
defaultRating
} = this.state;
this.updateIcon(defaultRating);
}
flag = true;
updateIcon = index => {
const {
resultRating
} = this.state;
const {
onPress
} = this.props;
let start = this.state.typeIcon[0];
let end = this.state.typeIcon[1];
if (index === 1 && this.flag) {
this.setState({
icon: [...new Array(index).fill(end), ...new Array(resultRating - index).fill(start)]
});
onPress?.(1);
this.flag = false;
} else if (index === 1 && !this.flag) {
this.setState({
icon: [...new Array(index - 1).fill(end), ...new Array(resultRating - index + 1).fill(start)]
});
this.flag = true;
onPress?.(0);
} else {
this.setState({
icon: [...new Array(index).fill(end), ...new Array(resultRating - index).fill(start)]
});
this.flag = true;
onPress?.(index);
}
};
render() {
return <View>
<View style={styles.RatingContainer}>
{this.state.icon.map((item, index) => {
return <TouchableOpacity onPress={() => {
this.updateIcon(index + 1);
}} key={index}>
{typeof item === 'string' ? <Icon name={item} color="#ebc445" size={this.state.size} /> : item}
</TouchableOpacity>;
})}
</View>
</View>;
}
}
const styles = StyleSheet.create({
RatingContainer: {
flexDirection: 'row'
}
});