让前端飞Web前端之路

react 实现tab 切换功能

2019-07-11  本文已影响184人  一只大橘

不断的蜕变只为遇见更好的自己,共勉。


tab.png
import React,{Component} from 'react';
import ReactDom from 'react-dom'
import Header from '../../compent/header'
// import Container from  '../container'
import '../../css/tabchange.css'

function RenderTabs(tabs,tab,changeTabs){
  return tabs.map((item, idx) => {
    if(!item.isshow){
      return null;
    }
    return(
        <li 
        key={item.index} 
        className ={ tab === idx ? 'active' :'' }  
        onClick={()=>{changeTabs(idx)}}>
        {item.name}{idx}
        </li>
    )
  })
}

function showMain(idx){
  switch (idx) {
    case 0:
      return <div>我是tab {idx}</div>
      break;
    case 1:
      return <div>我是tab {idx}</div>
      break;
    case 2:
      return <div>我是tab {idx}</div>
      break;
    default:
      break;
  }
}


class TabChange extends Component{
  constructor(props){
    super(props)

    const tabs =[
      {name:'tab',index:0,isshow:true},
      {name:'tab',index:1,isshow:true},
      {name:'tab',index:2,isshow:true}
    ]
    this.state={
      tab:0,
      tabs
    }
  }

  changeTabe=(idx)=>{
    console.log(idx);
    this.setState({
      tab:idx
    });
  }

 
  render(){
    const {tabs,tab} =this.state;
    return(
      <div className="tabchange-box">
        <Header title={'Tabchange'} haveNav={true}/>
        <ul>
          {RenderTabs(tabs,tab,this.changeTabe)}
        </ul>
        {showMain(tab)}
      </div>
    )
  }

}
export default TabChange;
//css
.tabchange-box{padding: 0px .2rem;}
.tabchange-box ul{display:flex;border-bottom: 1px solid #eee;flex-direction: row;}
.tabchange-box  ul li{text-align: center}
.tabchange-box  ul li.active{border-bottom: 2px solid rebeccapurple;color: rebeccapurple}
上一篇下一篇

猜你喜欢

热点阅读