react/tab切换

3,669 阅读1分钟

Tabs组件

index.js

import React from 'react';
import './style.less'

export default class Tabs extends React.Component {
    constructor(){
        super();
        this.state={
            currentIndex:0
        }
    }
    detailClickHandler(index){
        this.setState({
            currentIndex:index
        })
    }
    check_title_index=(index)=>{
        return this.state.currentIndex===index?'Tab_title active':'Tab_title'
    }
    check_item_index=(index)=>{
        return this.state.currentIndex===index?'show':'hide'
    }
    render() {
        return (
            <div>
                {/* tab的title */}
                <ul className="Tab_title_wrap">
                    {
                        React.Children.map(this.props.children, (ele, index) => {
                            return (
                                <li className={ this.check_title_index(index) } onClick={this.detailClickHandler.bind(this,index)}>
                                    {ele.props.lable}
                                </li>
                            )
                        })
                    }
                </ul>
                {/* tab的内容 */}
                <ul>
                    {
                        React.Children.map(this.props.children,(ele,index)=>{
                            return(
                                <li className={ this.check_item_index(index) }>
                                    {ele.props.children}
                                </li>
                            )
                        })
                    }
                </ul>
            </div>
        )
    }
} 

style.less

.Tab_title_wrap{
    display: flex;
    .Tab_title{
      flex: 1;
      text-align: center;
      font-size: 15px;
      margin: 20px;
      border: 2px solid #ff5555;
      padding: 10px;
      margin-bottom: 0;
    }
  }
  .hide{
    display: none;
  }
  .show{
    display: block;
  }
  

页面使用

import Tabs from '../../../components/Tabs';

<Tabs>
    <tab lable='商品信息'>
        <DetailCollect id={this.props.id}/>
    </tab>
    <tab lable='商品评价'>
        <DetailComment id={this.props.id}/>
    </tab>
</Tabs>