思路是一層實心星星襟交,覆蓋著空心星星雌团,控制實心星星的顯示寬度
直接上代碼
import React, { Component } from 'react';
import ReactNative, {
Image,
View,
} from 'react-native';
//這里使用了FontAwesome的字體庫顯示圖片褂始,請參考該組件的使用
export default class StarRating extends Component {
constructor(props) {
super(props);
this.total = this.props.total || 3; //星星的數(shù)量
this.starSize = this.props.starSize || 20; //星星的大小
this.starSpacing = this.props.starSpacing || 0; //星星之間的間隔
this.starColor = this.props.starColor || 'gold'; //星星的顏色
let stars = this.props.stars || 0; //評分
if (stars > this.total) {
stars = this.total;
}
this.state = {
stars: stars,
}
}
render() {
return <View style = {this.props.style}>
{this.renderEmptyStar()}
{this.renderFullStar()}
</View>
}
renderEmptyStar() {
//先展現(xiàn)一層空的星星,這里的icons方法參考下面一段代碼
let stars = [];
for (let i = 0; i < this.total; i++) {
stars.push(<View key={"star-o-" + i}>{
<Image style={[{ backgroundColor: 'yellow' ,marginLeft:this.starSpacing, height:this.starSize, width:this.starSize}]} />
}</View>);
}
return <View style={{ flexDirection: 'row', alignItems:'center' }}>{stars}</View>
}
renderFullStar() {
//按評分填充星星
let stars = [];
let width = Math.floor(this.state.stars) * (this.starSize * 0.93 + 2 * this.starSpacing)
if (this.state.stars > Math.floor(this.state.stars)) {
width += this.starSpacing;
width += this.starSize * 0.93 * (this.state.stars - Math.floor(this.state.stars));
}
for (let i = 0; i < this.total; i++) {
stars.push(<View key={"star-o-" + i}>{
<Image style={[{ backgroundColor: 'red' ,marginLeft:this.starSpacing, height:this.starSize, width:this.starSize}]} />
}</View>);
}
return <View style={{ flexDirection: 'row',position: 'absolute', alignItems:'center', overflow: 'hidden'}}>{stars}</View>
}
componentWillReceiveProps(nextProps) {
if (nextProps.stars !== this.props.stars) {
let stars = nextProps.stars || 0;
if (stars > this.total) {
stars = this.total;
}
this.setState({
stars: stars
});
}
}
}