Renders a star rating component.
- Define a component, called
Star
that will render each individual star with the appropriate appearance, based on the parent component’s state. - In the
StarRating
component, use theReact.useState()
hook to define therating
andselection
state variables with the initial values ofprops.rating
(or0
if invalid or not supplied) and0
. - Create a method,
hoverOver
, that updatesselected
andrating
according to the providedevent
. - Create a
<div>
to wrap the<Star>
components, which are created usingArray.prototype.map
on an array of 5 elements, created usingArray.from
, and handle theonMouseLeave
event to setselection
to0
, theonClick
event to set therating
and theonMouseOver
event to setselection
to thestar-id
attribute of theevent.target
respectively. - Finally, pass the appropriate values to each
<Star>
component (starId
andmarked
).
代码实现
function Star({ marked, starId }) {
return (
<span star-id={starId} style={{ color: '#ff9933' }} role="button">
{marked ? '\u2605' : '\u2606'}
</span>
);
}
function StarRating(props) {
const [rating, setRating] = React.useState(typeof props.rating == 'number' ? props.rating : 0);
const [selection, setSelection] = React.useState(0);
const hoverOver = event => {
let val = 0;
if (event && event.target && event.target.getAttribute('star-id'))
val = event.target.getAttribute('star-id');
setSelection(val);
};
return (
<div
onMouseOut={() => hoverOver(null)}
onClick={event => setRating(event.target.getAttribute('star-id') || rating)}
onMouseOver={hoverOver}
>
{Array.from({ length: 5 }, (v, i) => (
<Star
starId={i + 1}
key={`star_${i + 1} `}
marked={selection ? selection >= i + 1 : rating >= i + 1}
/>
))}
</div>
);
}
使用样例
ReactDOM.render(<StarRating />, document.getElementById('root'));
ReactDOM.render(<StarRating rating={2} />, document.getElementById('root'));