Это компонент StarRating, написанный с помощью ReactJS и Hooks:
Демо по адресу: https://codesandbox.io/s/laughing-wescoff-mtf9j?file=/src/StarRating.js
Это небольшое улучшение по сравнению со страницей обзора продукта Amazon.com, поскольку на ней рейтинг в звездах не меняется вместе с перемещением мыши пользователя.
Я не довел до совершенства каждую деталь, но вот код:
// StarRating.js
export default function StarRating({ numTotalStars = 5, initialRating = 0 }) {
const [numSelectedStars, setNumSelectedStars] = useState(initialRating);
const [numHoveringStars, setNumHoveringStars] = useState(null);
const [isUserHovering, setIsUserHovering] = useState(false);
function getColor(isUserHovering, i, numSelectedStars, numHoveringStars) {
const threshold = isUserHovering ? numHoveringStars : numSelectedStars;
return (i < threshold) ? "red" : "grey";
}
return (
<div className="star-rating">
<div onMouseEnter={() => setIsUserHovering(true)} onMouseLeave={() => setIsUserHovering(false)} >
{Array.from({ length: numTotalStars }).map((e, i) =>
<Star
key={i}
color={getColor(isUserHovering, i, numSelectedStars, numHoveringStars)}
handleSelect={() => setNumSelectedStars(i + 1)}
handleHover={() => setNumHoveringStars(i + 1)}
/>)}
</div>
<div className="label">rating {numSelectedStars}</div>
</div>
);
}
и другой файл:
// Star.js
import { FaStar } from "react-icons/fa";
export default function Star({ color = "grey", handleSelect = () => { }, handleHover = () => { } }) {
return (
<FaStar className="star-rating-star"
color={color}
onMouseOver={handleHover}
onClick={handleSelect}
/>
);
}
К нему предъявляются следующие требования:
// Requirements:
// 1) The initial stars should be displayed
// 2) When the user enters the area, the same red color shows how many stars, and follows the user's mouse movement
// 3) When the user clicks the number of stars, the number of stars and rating becomes this new rating
// 4) If the user moves away and moves back in, now the user should be able to alter the rating again