雖然只是一個(gè)簡(jiǎn)單的功能,還是記錄一下比較好。頁(yè)面上有很多個(gè)li,要實(shí)現(xiàn)點(diǎn)擊到哪個(gè)就哪個(gè)高亮。當(dāng)年用jq的時(shí)候,也挺簡(jiǎn)單的,就是選中的元素給addClass,然后它的兄弟元素removeClass,再寫個(gè)active的樣式就搞定了。那現(xiàn)在用react要實(shí)現(xiàn)類似的操作,我想到的就是用一個(gè)currentIndex,通過判斷currentIndex在哪個(gè)元素實(shí)現(xiàn)切換。
先上一下效果圖:

代碼:
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 = ['產(chǎn)品調(diào)整', '接口流量', '負(fù)載均衡', '第三方軟件調(diào)整', '安全加固', '性能控制', '日志查詢', '業(yè)務(wù)分析']; 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; } }是不是很簡(jiǎn)單呢。就是在生成這些li的時(shí)候給元素添加一個(gè)index標(biāo)志位,然后點(diǎn)擊的時(shí)候,把這個(gè)index用event.currentTarget.getAttribute('index')取出來,然后去設(shè)置currentIndex的值,再寫一寫css的active樣式就搞定了。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注