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 

            {this.renderEmptyStar()}

            {this.renderFullStar()}

        

    }

    renderEmptyStar() {

        //先展现一层空的星星,这里的icons方法参考下面一段代码

        let stars = [];

        for (let i = 0; i < this.total; i++) {

            stars.push({

                

            });

        }

        return {stars}

    }

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

                

            });

        }

        return {stars}

    }

    componentWillReceiveProps(nextProps) {

        if (nextProps.stars !== this.props.stars) {

            let stars = nextProps.stars || 0;

            if (stars > this.total) {

                stars = this.total;

            }

            this.setState({

                stars: stars

            });

        }

    }

}

你可能感兴趣的:(React 星星评分控价)