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>
);
}
}
版权声明:本文为weixin_43845137原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。