Rumah  >  Artikel  >  hujung hadapan web  >  react实现选中li高亮步骤详解

react实现选中li高亮步骤详解

php中世界最好的语言
php中世界最好的语言asal
2018-05-24 13:40:312627semak imbas

这次给大家带来react实现选中li高亮步骤详解,react实现选中li高亮的注意事项有哪些,下面就是实战案例,一起来看一下。

虽然只是一个简单的功能,还是记录一下比较好。页面上有很多个li,要实现点击到哪个就哪个高亮。当年用jq的时候,也挺简单的,就是选中的元素给addClass,然后它的兄弟元素removeClass,再写个active的样式就搞定了。那现在用react要实现类似的操作,我想到的就是用一个currentIndex,通过判断currentIndex在哪个元素实现切换。
先上一下效果图:

clipboard.png
代码:

    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 ? &#39;active&#39; : &#39;&#39;}
                              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样式就搞定了。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

React结合TypeScript和Mobx步骤详解

React-router v4使用步骤详解

Atas ialah kandungan terperinci react实现选中li高亮步骤详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:PromiseA+的实现步骤详解Artikel seterusnya:前端中排序算法实例详解