虽然只是一个简单的功能, 还是记录一下比较好. 页面上有很多个 li, 要实现点击到哪个就哪个高亮. 当年用 jq 的时候, 也挺简单的, 就是选中的元素给 addClass, 然后它的兄弟元素 removeClass, 再写个 active 的样式就搞定了. 那现在用 react 要实现类似的操作, 我想到的就是用一个 currentIndex, 通过判断 currentIndex 在哪个元素实现切换.
先上一下效果图:
代码:
- 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 部分
- .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 样式就搞定了.
来源: http://www.jb51.net/article/140735.htm