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;
     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樣式就搞定了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM