React轮播选项卡

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值