react 之简单的tab组件

react 之简单的tab组件

在这里插入图片描述

TabControl组件

import React, { Component } from 'react';

import "./tab.scss"
import PtopTypes from "prop-types";
export default class TabControl extends Component {
  static proptype = {
    title:PtopTypes.array.isRequired,
  };

  state = {
    currentIndex:0
  }

  itemClick = (currentIndex) => {
    console.log('子组件',currentIndex);
    this.setState({
      currentIndex
    })
    // 向父组件传递数据 函数
    this.props.itemClick(currentIndex);
  }

 render(){
   const { title  } = this.props;
   const { currentIndex } = this.state;
   return (
     <div className="tab-control">
       {
         title.map((item,idx) => {
           return (
            <div className="tab-item" key={item} onClick={ e => this.itemClick(idx)}>
              <span className={ "title " + (currentIndex == idx ? "active": "" ) } >{item}</span>
            </div>
           )
         })
       }
     </div>
   )
 }
}
.tab-control {
  height: 40px;
  line-height: 40px;
  display: flex;
}

.tab-control .tab-item {
  flex: 1;
  text-align: center;
}

.tab-control .title {
  padding: 3px 5px;
}

.tab-control .title.active {
  color: red;
  border-bottom: 3px solid red;
}

app父组件

import React, { Component } from "react";

import TabControl from "./component/TabControl/TabControl";
import PtopTypes from "prop-types";

export default class App extends Component {
  static proptype = {
    itemClick: PtopTypes.func.isRequired,
  };
  title = ["玄幻", "武侠", "校园"];
  state = {
    currentTitle: "玄幻",
  };

  // 子组件向父组件(app)传递函数
  itemClick = (idx) => {
    // console.log("父组件idx", idx);
    this.setState({
      currentTitle: this.title[idx],
    });
  };

  render() {
    const title = this.title;
    const { currentTitle } = this.state;
    return (
      <div>
        <TabControl title={title} itemClick={(idx) => this.itemClick(idx)} />
        <h2>{currentTitle} </h2>
      </div>
    );
  }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值