react實現選中的li高亮

雖然只是一個簡單的功能,仍是記錄一下比較好。頁面上有不少個li,要實現點擊到哪一個就哪一個高亮。當年用jq的時候,也挺簡單的,就是選中的元素給addClass,而後它的兄弟元素removeClass,再寫個active的樣式就搞定了。那如今用react要實現相似的操做,我想到的就是用一個currentIndex,經過判斷currentIndex在哪一個元素實現切換。
先上一下效果圖:css

clipboard.png
代碼:react

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樣式就搞定了。負載均衡

相關文章
相關標籤/搜索