react 之简单的tab组件
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ff5648909c7b52a6a3a213a081ce6eac.png#pic_center)
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: "玄幻",
};
itemClick = (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>
);
}
}