选中与非选中状态转换

这篇博客探讨了如何使用React实现一个标签选择组件,包括样式定义和状态管理。`handleList`函数用于初始化列表项的状态,`LabelSelect`组件处理点击事件以切换选中状态。代码中展示了React组件的渲染逻辑,以及CSS样式的应用。
摘要由CSDN通过智能技术生成
.root {
  display: flex;
  flex-wrap: wrap;
  span {
    padding: 4px 12px;
    color: rgba(0, 0, 0, 0.5);
    font-size: 12px;
    font-family: PingFangSC-Regular;
    line-height: 14px;
    border: 1px solid rgba(0, 0, 0, 0.2);
    cursor: pointer;
    margin-bottom: 8px;
  }
  .active {
    padding: 4px 12px;
    color: #fff;
    font-size: 12px;
    line-height: 14px;
    background: #0055ff;
    cursor: pointer;
  }
}

import React, { useState } from 'react';
import styles from './index.less';


const handleList = (newList) => {
  const tempt = [];
  newList.forEach((item) => {
    tempt.push({
      label: item,
      isChecked: false,
    });
  });
  return tempt;
};
const LabelSelect = (props) => {
  const { list } = props; // list格式 ['例子1','例子2']
  const [labelList, setLabelList] = useState(handleList(list));

  const clickTag = (i) => {
    const tempt = [...labelList];
    labelList.forEach((item, index) => {
      if (index === i) {
        tempt[i].isChecked = !tempt[i].isChecked;
      }
    });
    setLabelList(tempt);
  };
  return (
    <div className={styles.root}>
      {
        labelList.map((item, index) => (
          <span
            onClick={() => clickTag(index)}
            className={item.isChecked && styles.active}
            key={index}
            style={{ marginRight: '8px' }}
          >
            {item.label}
          </span>
        ))
      }
    </div>
  );
};

export default LabelSelect;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值