React切换选中项效果

2021-04-17 20:28:11
React切换选中项 ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React切换选中项</title> <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script> <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="root"></div> <style> .active{color: #4290f4} li{cursor: pointer; float: left; list-style: none; padding: 10px} </style> <script type="text/babel"> class App extends React.Component{ state = { nav: ['国内新闻', '国际新闻', '科技频道'], activeIndex: 0 // 当前选中项的索引值 } handleClick = (ind)=>{ this.setState({activeIndex: ind}) } render(){ return ( <ul> {this.state.nav.map((item, index)=>{ return <li key={index} className={this.state.activeIndex == index ? 'active': ''} onClick={()=>{this.handleClick(index)}}>{item}</li> })} </ul> )} } let el = <App /> let root = document.getElementById('root'); ReactDOM.render(el, root); </script> </body> </html> ```