怎么用react写tab切换
实现思路:
1、创建一个TabChange组件,定义组件的状态;
2、写一个changeTabe函数用于改变组件状态;
3、在RenderTabs函数中绘制页面及绑定事件;
4、当组件点击时触发changeTabs即可实现切换。
效果:
代码如下:
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}
更多React相关技术文章,请访问React答疑栏目进行学习!
以上就是怎么用react写tab切换的详细内容,更多请关注易知道|edz.cc其它相关文章!