如何在Reactjs中创建基于平均(十进制)的星级?

时间:2019-07-01 09:27:41

标签: reactjs

我创建了星级评定功能,该功能适用​​于整个整数。但我想对其进行修改并实现平均星级评定功能。基于小数点的功能。在下面的代码中,“已选择”道具值取为2.5,但是如何显示每个十进制值(如2.5、3.4、2.3等)的一半选中的星星?

这是代码:

import React from "react";
import ReactDOM from "react-dom";
import PropTypes from "prop-types";
import './style.scss'

const Star = ({ selected = false, onClick = f => f }) => {
  console.log("selected : ", selected);

  return (
    <div className={selected ? "store-card-rating selected" : "store-card-rating"} onClick={onClick} ><i className="fas fa-star empty-star"/></div>
  );
};

Star.propTypes = {
    selected: PropTypes.bool,
    onClick: PropTypes.func
  };
  
  class StarRating extends React.Component {
    constructor(props) {
      super(props);
      this.state = { starsSelected :this.props.Selected};
      this.change = this.change.bind(this);
    }
  
    change(starsSelected) {
      this.setState({ starsSelected: starsSelected });
    }
  
    render() {
      const { totalStars } = this.props;
      const { starsSelected } = this.state;
  
      return (
        <div className="star-rating">
          {[...Array(totalStars)].map((n, i) => (
            <Star
              key={i}
              selected={i < starsSelected}
              onClick={() => this.change(i + 1)}
            />
          ))}
          <p>
            {starsSelected} of {totalStars} stars
          </p>
        </div>
      );
    }
  }
  
  StarRating.propTypes = {
    totalStars: PropTypes.number
  };
  
  StarRating.defaultProps = {
    totalStars: 5
  };

const rootElement = document.getElementById("root");
ReactDOM.render(<StarRating totalStars={5} Selected={2} />, rootElement);

  

1 个答案:

答案 0 :(得分:0)

解决方案1 ​​

有一个名为react-rating的很棒的程序包,它基于FontAwesome图标完全满足您的需求。

解决方案2

假设可以,则可以设计星星右侧部分的.1到.9部分,并将其显示在已显示的全星上(例如,灰色)。它可能看起来像这样(有心): .2 of a heart .9 of a heart