import React, { Component } from 'react'
import './index.less'
//定义数据类型
interface Props { }
interface Title {
ID: string,
CON: string
}
interface Content {
ID: string,
CON: string
}
interface State {
BtnIndex: number,
TitleList: Title[],
ContentList: Content[]
}
class Tab extends Component<Props, State> {
//创建定时器
timer!: NodeJS.Timeout;
//创建数据
constructor(props: Props) {
super(props);
this.state = {
BtnIndex: 0,
TitleList: [
{ ID: 'a1', CON: '选项一' },
{ ID: 'a2', CON: '选项二' },
{ ID: 'a3', CON: '选项三' }
],
ContentList: [
{ ID: 'b1', CON: '内容一' },
{ ID: 'b2', CON: '内容二' },
{ ID: 'b3', CON: '内容三' }
]
}
}
//更新下标
TabIndex(index: number) :void {
this.setState({
BtnIndex: index
})
}
//开启定时器
funIndex() {
let Index = this.state.BtnIndex
if (Index >= this.state.TitleList.length - 1) {
Index = 0
} else {
Index++
}
this.setState({
BtnIndex: Index
})
}
funStart() {
this.timer = setInterval(() => {
this.funIndex()
}, 1000)
}
componentDidMount(){
this.funStart()
}
//清除定时器
clearTimer=()=>{
clearInterval(this.timer)
}
render() {
let BtnIndex = this.state.BtnIndex
let TitleList = this.state.TitleList
let ContentList = this.state.ContentList
return (
<div className='tab' onMouseEnter={this.clearTimer.bind(this)} onMouseLeave={this.componentDidMount.bind(this)}>
{
TitleList.map((item, index) => <li onClick={this.TabIndex.bind(this, index)} key={item.ID} className={BtnIndex === index ? 'tab-button' : ''}>{item.CON}</li>)
}
{
ContentList.map((item, index) => <div key={item.ID} className={'tab-text'} style={{ display: BtnIndex === index ? 'block' : 'none' }}>{item.CON}</div>)
}
</div>
)
}
}
export default Tab
css
.tab .tab-button {
background-color: red;
color: #fff;
}
.tab .tab-text {
width: 600px;
height: 200px;
font-size: 30px;
line-height: 200px;
text-align: center;
display: none;
}
body,
ul,
li,
div {
margin: 0;
padding: 0;
}
.tab {
width: 600px;
height: 300px;
border: 1px solid red;
margin: 50px auto;
}
.tab li {
width: 198px;
height: 50px;
line-height: 50px;
list-style: none;
text-align: center;
float: left;
border: 1px solid red;
cursor: pointer;
}