react實現(xiàn)點擊選中的li高亮的示例代碼
雖然只是一個簡單的功能,還是記錄一下比較好。頁面上有很多個li,要實現(xiàn)點擊到哪個就哪個高亮。當年用jq的時候,也挺簡單的,就是選中的元素給addClass,然后它的兄弟元素removeClass,再寫個active的樣式就搞定了。那現(xiàn)在用react要實現(xiàn)類似的操作,我想到的就是用一個currentIndex,通過判斷currentIndex在哪個元素實現(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)整', '接口流量', '負載均衡', '第三方軟件調(diào)整',
'安全加固', '性能控制', '日志查詢', '業(yè)務分析'];
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樣式就搞定了。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
windows下create-react-app 升級至3.3.1版本踩坑記
這篇文章主要介紹了windows下create-react-app 升級至3.3.1版本踩坑記,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02
React報錯Type '() => JSX.Element[]&apos
這篇文章主要為大家介紹了React報錯Type '() => JSX.Element[]' is not assignable to type FunctionComponent解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
react中通過props實現(xiàn)父子組件間通信的使用示例
在React中,父組件可以通過props屬性向子組件傳遞數(shù)據(jù),子組件可以通過props屬性接收父組件傳遞過來的數(shù)據(jù),本文就來介紹一下如何實現(xiàn),感興趣的可以了解一下2023-10-10
關于react-router/react-router-dom v4 history不能訪問問題的解決
這篇文章主要給大家介紹了關于react-router/react-router-dom v4 history不能訪問問題的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧。2018-01-01

