Home >Web Front-end >JS Tutorial >Detailed explanation of steps to highlight click-selected li in react
This time I will bring you a detailed explanation of the steps to highlight the li selected by clicking in react, and highlight the li selected by clicking in react. What are the precautions?The following is a practical case, let's take a look.
Although it is just a simple function, it is better to record it. There are many li's on the page, and the one you click on will be highlighted. When I used jq back then, it was quite simple. I just added the selected element to addClass, then removed its sibling element, and then wrote an active style. Now to use react to implement similar operations, what I think of is to use a currentIndex and switch by judging which element the currentIndex is on.
First look at the renderings:
Code:
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 part
.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; } }
Isn’t it very simple? . It is to add an index flag to the element when generating these li, and then when clicked, use event.currentTarget.getAttribute('index') to take out the index, then set the value of currentIndex, and then write css The active style is done.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of the steps to use the JS array method
Detailed explanation of the steps to use the JS string method
The above is the detailed content of Detailed explanation of steps to highlight click-selected li in react. For more information, please follow other related articles on the PHP Chinese website!