当前位置: 移动技术网 > IT编程>开发语言>JavaScript > react实现点击选中的li高亮的示例代码

react实现点击选中的li高亮的示例代码

2018年05月29日  | 移动技术网IT编程  | 我要评论

古玉网,高树三姊妹续,亲前婚后19楼

虽然只是一个简单的功能,还是记录一下比较好。页面上有很多个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;
        width: 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样式就搞定了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网