React 之 PK 组件

222 阅读1分钟

我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

分为三个部分,left, center, right。

left 和 right 比较好理解,center 这个 dom 结构主要是为了说可能中间需要添加一些自定义的图片之类的,这个 dom 不是必须的。大家可以根据自己的需求进行添加。

传入的数据结构

const list = [
  {
    id: 3,
    content: '男性',
    count: 18,
  },
  {
    id: 4,
    content: '女性',
    count: 1,
  },
];

比较容易理解。

left, right 使用 flex 布局。

.wrapper {
  .pk-wrapper {
    width: 100%;
    height: 52px;
    display: flex;
    position: relative;
    .left,
    .right {
      height: 52px;
      min-width: 104px;
      display: flex;
      justify-content: center;
      flex-direction: column;
      text-align: center;
      line-height: 22px;
      align-items: center;
    }
  }
}

dom 结构中,center 是位于 left 中。这样的做法是可以使得我们不需要去计算 center 的位置,只需要给 cneter 添加一个绝对定位,right 的数值为本身 width 的一半即可。

.left {
  position: relative;
  .center-img {
    position: absolute;
    right: -18px;
    img {
      height: 52px;
      width: 36px;
    }
  }
}

接下来我们来看一下具体的 dom 结构。

<div className="pk-wrapper">
  <div
    className="left"
    style={{
      width: `${leftContent.percent}%`,
    }}
  >
    <span>{Math.round(leftContent.percent)}%</span>
    {leftContent.optionName}
    <div className='center-img'>
      <img width={16} src={"https://bpic.588ku.com/element_origin_min_pic/19/12/21/355630ef91dca5956d42200ad11f9057.jpg"} alt="center" />
    </div>
  </div>
  <div
    className="right"
    style={{
      width: `${rightContent.percent}%`,
    }}
  >
    <span>{Math.round(rightContent.percent)}%</span>
    {rightContent.optionName}
  </div>
</div>

处理数据

页面有数据

各自数据占整体的百分比

(dataItem.count / sum.current) * 100

页面无数据

默认 percent 为 50%,这样页面也会好看一点

useEffect(() => {
  sum.current = list[0].count + list[1].count
  let arr = []
  // 两个相加为 0,代表页面无数据
  if (sum.current === 0) {
    arr = list.map((dataItem) => {
      return {
        ...dataItem,
        optionName: dataItem.content,
        percent: 50,
        count: 0,
      }
    })
  } else {
    arr = list.map((dataItem) => {
      return {
        ...dataItem,
        optionName: dataItem.content,
        percent: (dataItem.count / sum.current) * 100,
        count: dataItem.count,
      }
    })
  }
}

图片网上随便找的,各位可以根据自己的具体情况进行替换。

图片.png