我在网上找到了这个组件,它创建了一个评审组件,但它不起作用。
import { useState } from 'react';
const Star = ({filled, starId}) => (
<span star-id={starId} style={{ color: '#ff9933' }} role="button">
{filled ? 'u2605' : 'u2606'}
</span>
);
export const Rating = props => (
const [rating, setRating] = useState(typeof props.rating == 'number' ? props.rating : 0);
const [selection, setSelection] = 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} `}
filled={selection ? selection >= i + 1 : rating >= i + 1}
/>
))}
</div>
);
它为这行抛出一个错误:
const [rating, setRating] = useState(typeof props.rating == 'number' ? props.rating : 0);
它怎么了?如何修复?
我认为钩子很好,但您需要围绕函数体使用{}
:
export const Rating = props => {
const [rating, setRating] = useState((typeof props.rating === 'number') ? props.rating : 0);
const [selection, setSelection] = 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} `}
filled={selection ? selection >= i + 1 : rating >= i + 1}
/>
))}
</div>
);
};
代码沙箱
您应该考虑的第二件事是:您可能应该使用===
而不是==
进行typeof
检查。