react 給選中的li添加樣式


思路:使用事件委托,
關鍵:獲取到的index必須轉為數字,因為它是字符串
handleClick = (e) => {
const nodeName = e.target.nodeName.toUpperCase()
let tag = e.target;
if (nodeName === 'LI') {
let index = parseInt(tag.getAttribute('index'))
this.setState({
currentIndex: index
})
}
}


import React from 'react'
import './nav.scss'

class NavCom extends React.Component {
constructor(props) {
super(props)
this.state = {
currentIndex: 0
}
}
sestCurrentStyle = (index) => {
return this.state.currentIndex === index ? 'current' : ''
}
handleClick = (e) => {
const nodeName = e.target.nodeName.toUpperCase()
let tag = e.target;
if (nodeName === 'LI') {
let index = parseInt(tag.getAttribute('index'))
this.setState({
currentIndex: index
})
}
}
render() {
const navList = this.props.navList
return (
<div className='nav-wrap' onClick={(e)=>this.handleClick(e)}>
{
navList && navList.map( (item, index) => {
return (
<li key={index} index={index} className={this.state.currentIndex === index ? 'current' : ''}>{item}</li>
)
})
}
</div>
)
}
}
export default NavCom


免責聲明!

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



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