学无先后,达者为师

网站首页 编程语言 正文

React实现Tab栏切换

作者:田本初 更新时间: 2023-10-12 编程语言

前言

特殊需求下,由于组件的Tab栏改动过于繁琐,需要原生写,下面是React实现Tab栏的demo。

实现

  1. 声明一个currentId用于标识当前选中项
  2. 根据currentId动态控制样式
  3. 根据currentId动态展示内容

.jsx

import React, { useState } from "react"

const Nav = () => {
  const [currentId, setCurrentId] = useState(1)
  const options = [
    { label: "选项一", id: 1 },
    { label: "选项二", id: 2 },
    { label: "选项三", id: 3 },
    { label: "选项四", id: 4 },
  ]
  const changeId = (id) => {
    setCurrentId(id)
  }
  return (
    <div className="test_box">
      {/* Tab栏 */}
      <ul className="test_nav">
        {options.map((item) => {
          return (
            <li
              key={item.id}
              onClick={() => changeId(item.id)}
              className={item.id == currentId ? "active" : ""}
            >
              {item.label}
            </li>
          )
        })}
      </ul>
      {/* 内容区域 */}
      <div style={{ height: 200, backgroundColor: "pink" }}>
        <div style={{ display: currentId == 1 ? "block" : "none" }}>内容一</div>
        <div style={{ display: currentId == 2 ? "block" : "none" }}>内容二</div>
        <div style={{ display: currentId == 3 ? "block" : "none" }}>内容三</div>
        <div style={{ display: currentId == 4 ? "block" : "none" }}>内容四</div>
      </div>
    </div>
  )
}

export default Nav

css

.test_box{
  width: 500px;
  border: 1px solid #333;

  .test_nav{
    display: flex;
    justify-content: space-around;
    list-style: none;
    margin: 0;

    li{
      width: 150px;
      height: 50px;
      text-align: center;
      line-height: 50px;
      cursor: pointer;
    }

    .active{
      background-color: skyblue;
      position: relative;
      &::after{
        content:"";
        display: inline-block;
        position: absolute;
        width: 60%;
        bottom: 0;
        left: 20%;
        border-bottom: 2px solid red;
      }
    }

  }
  
}

原文链接:https://blog.csdn.net/owo_ovo/article/details/132305369

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新