zoukankan      html  css  js  c++  java
  • react实现点击选中的li高亮

    虽然只是一个简单的功能,还是记录一下比较好。页面上有很多个li,要实现点击到哪个就哪个高亮。当年用jq的时候,也挺简单的,就是选中的元素给addClass,然后它的兄弟元素removeClass,再写个active的样式就搞定了。那现在用react要实现类似的操作,我想到的就是用一个currentIndex,通过判断currentIndex在哪个元素实现切换。

     class Category extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          currentIndex: 0
        }
        this.setCurrentIndex = this.setCurrentIndex.bind(this)
      }
      setCurrentIndex(event) {
        this.setState({
          currentIndex: parseInt(event.currentTarget.getAttribute('index'), 10)
        })
      }
      render() {
        let categoryArr = ['产品调整', '接口流量', '负载均衡', '第三方软件调整',
                  '安全加固', '性能控制', '日志查询', '业务分析'];
        let itemList = [];
        for(let i = 0; i < categoryArr.length; i++) {
          itemList.push(<li key={i}
                   className={this.state.currentIndex === i ? 'active' : ''}
                   index={i} onClick={this.setCurrentIndex}
                 >{categoryArr[i]}</li>);
        }
        return <ul className="category">{itemList}</ul>
      }
    }
    

      css

    .category {
       padding-left: 0;
       &:after {
         content: '';
         display: block;
         clear: both;
       }
       li {
         float: left;
          23%;
         height: 40px;
         margin-right: 10px;
         margin-bottom: 10px;
         border: 1px solid $border-color;
         list-style: none;
         color: $font-color;
         line-height: 40px;
         text-align: center;
         font-size: 14px;
         cursor: pointer;
         &.active {
           border-color: #079ACD;
         }
      }
    

      就是在生成这些li的时候给元素添加一个index标志位,然后点击的时候,把这个index用event.currentTarget.getAttribute('index')取出来,然后去设置currentIndex的值,再写一写css的active样式就搞定了。

  • 相关阅读:
    浅谈LBS(基于位置的服务)
    MapBar地图更新啦
    推荐一款软件:Global Mapper
    51ditu、清华地图以及Google地图
    极索(Gsuo)推出新版地图采用Gmap设计思路
    公告:Rover's Official Blog停止更新
    最后的礼物:校园多媒体系统和校园WEBGIS系统
    JAVA中最常用的十个快捷键
    启程去旅行 android之merge布局 http://www.cnblogs.com/travelfromandroid/articles/2133206.html
    Http 范例
  • 原文地址:https://www.cnblogs.com/taxun/p/13255688.html
Copyright © 2011-2022 走看看