React 星星评分控价

思路是一层实心星星,覆盖着空心星星,控制实心星星的显示宽度

直接上代码


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; //星星的数量

        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() {

        //先展现一层空的星星,这里的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

            });

        }

    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。