内容简介:本文译自:星级评分组件。星星组件:
本文译自: 30-seconds-of-react 。 React 30 秒速学: 精选有用的 React 片段,30-seconds-of-react 的中文版本,已全部完成翻译、上线,地址: 30-seconds-of-react-zh_CN-umi 。
星级评分组件。
- 定义一个名为“Star”的组件,它将根据父组件的状态为每个星形呈现适当的外观。
-
在
StarRating组件中,使用React.useState()钩子来定义rating和selection状态变量,初始值为props.rating(如果无效或未传入,则为 0 )和 0 。 -
创建一个方法
hoverOver,根据传入的event更新selected和rating。 -
创建一个
<div>来包装<Star>组件,这些组件是使用Array.prototype.map在5个元素的数组上创建的,使用Array.from创建,并处理onMouseLeave将selection设置为0的事件,onClick事件设置rating和onMouseOver事件,分别将selection设置为event.target的star-id属性。 -
最后,将适当的值传递给每个
<Star>组件(starId和marked)。
星星组件:
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}
>
{/* 创建5个组件 */}
{Array.from({ length: 5 }, (v, i) => (
<Star
starId={i + 1}
key={`star_${i + 1} `}
marked={selection ? selection >= i + 1 : rating >= i + 1}
/>
))}
</div>
);
}
复制代码
例子
export default function() {
return <div>
<StarRating />
<StarRating rating={2} />
</div>;
}
复制代码
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Pro Django
Marty Alchin / Apress / 2008-11-24 / USD 49.99
Django is the leading Python web application development framework. Learn how to leverage the Django web framework to its full potential in this advanced tutorial and reference. Endorsed by Django, Pr......一起来看看 《Pro Django》 这本书的介绍吧!