tab页签-代码部分
child
import React,{useEffect, useState} from 'react'
const Child = (props: any) => {
const [loading,setLoading] = useState(true)
useEffect(()=>{
setTimeout(()=>{
setLoading(false)
},2000)
},[])
return (
<div>
{loading ? 'loading...': '我加载咯'}
</div>
)
}
export default Child
tab-item
import React, { useEffect, useState } from 'react'
const TabItem = (props: any) => {
const {index,animate} = props
const [visible,setVisible] = useState(false)
useEffect(()=>{
if(props.visible) {
setVisible(true)
}
},[props.visible])
let leftIndex = animate ? index*100+'%' : ''
return (
<div className={"tab-div__children " + (props.visible ? 'show':'')} style={{left: leftIndex}}>
{ visible && props.children}
</div>
)
}
export default TabItem
tab
import React, { useState } from 'react'
import './index.scss'
const Tab = (props: any) => {
const {topBars,onChangeKeys,activeKey,animate} = props
const [index,setIndex] = useState(0)
const liArr = topBars.map((item: any,index: number) => {
return <li key={index} className={item===activeKey ? "active": ""} onClick={() => {onChangeKeys(item);setIndex(index)}}>{item}</li>
})
let mapChild = props.children.map((item: any,index: number) =>
{
return React.cloneElement(item,{...item.props,visible:activeKey===item.key,index,animate: props.animate},item.props.children)
}
)
const marginLeft = animate ? (-index*100+'%'): ''
return (
<div className="tab">
<ul>
{liArr}
</ul>
<div className={`tab-div ${animate? 'animate':''}`} style={{marginLeft}} >
{
mapChild
}
</div>
</div>
)
}
export default Tab
Index
import React,{useState} from 'react'
import Tab from './tab'
import TabItem from './tab-item'
import Child from './child'
const Index = () => {
const [topBars,setTopBars] = useState(['aaa','bbb','ccc'])
const [activeKey,setActiveKey] = useState('aaa')
const handleChangeKey = (activeKey: string) => {
setActiveKey(activeKey)
}
return (
<Tab
topBars={topBars}
activeKey={activeKey}
onChangeKeys={handleChangeKey}
animate={false}
>
{topBars.map((item,index) => {
return (
<TabItem key={item} activeKey={item}>
<Child />
</TabItem>
)
})}
</Tab>
)
}
export default Index
Index.scss
$prefixCls: 'tab';
.#{$prefixCls} {
width: 276px;
height: 200px;
overflow: hidden;
ul {
li {
float: left;
margin: 0 10px;
border: 1px solid #ccc;
width: 70px;
text-align: center;
cursor: pointer;
&.active {
background-color: skyblue;
}
&:hover {
background-color: skyblue;
}
}
}
&-div {
&.animate {
transition: all 0.5s;
.tab-div__children {
visibility: visible;
}
}
position: relative;
width: 100%;
&__children {
visibility: hidden;
position: absolute;
top: 25px;
width: 276px;
height: 200px;
&:nth-child(1) {
background-color: skyblue;
}
&:nth-child(2) {
background-color: red;
}
&:nth-child(3) {
background-color: yellowgreen;
}
&.show {
visibility: visible;
}
}
}
}