React 30 秒速学:制作星级评分组件

栏目: 服务器 · 发布时间: 7年前

内容简介:本文译自:星级评分组件。星星组件:

本文译自: 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>;
}
复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Agile Web Development with Rails, Third Edition

Agile Web Development with Rails, Third Edition

Sam Ruby、Dave Thomas、David Heinemeier Hansson / Pragmatic Bookshelf / 2009-03-17 / USD 43.95

Rails just keeps on changing. Rails 2, released in 2008, brings hundreds of improvements, including new support for RESTful applications, new generator options, and so on. And, as importantly, we’ve a......一起来看看 《Agile Web Development with Rails, Third Edition》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具