网络编程 
首页 > 网络编程 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

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

先上一下效果图:

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

代码:

  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 "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样式就搞定了。

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

上一篇:karma+webpack搭建vue单元测试环境的方法示例
下一篇:浅谈Webpack 是如何加载模块的
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网