日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新