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