App.js
/*
* @Description:
* @Version: 2.0
* @Autor: sun
* @Date: 2022-10-14 22:21:24
* @LastEditTime: 2022-10-16 00:06:12
*/
import React, { Component } from 'react'
import TabControl from './TabControl'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
currentTitle: "新歌",
list: ["新歌", "精选", "流行"]
}
}
render() {
const { currentTitle, list } = this.state
return (
<div>
<TabControl itemClick={ index => this.itemClick(index) } titles={ list }/>
<h2>{ currentTitle }</h2>
</div>
)
}
itemClick(index) {
this.setState({
currentTitle: this.state.list[index]
})
}
}
TabControl.js
/*
* @Description:
* @Version: 2.0
* @Autor: sun
* @Date: 2022-10-15 23:41:22
* @LastEditTime: 2022-10-16 01:17:57
*/
import React, { Component } from 'react'
import propTypes from 'prop-types'
import './style.css'
export default class TabControl extends Component {
constructor(props) {
super(props);
this.state = {
currentIndex: 0,
}
}
render() {
const { titles } = this.props
const { currentIndex } = this.state
return (
<div className='tab-control'>
{
titles.map((item, index) => {
return (
<div key={item}
className={ "tab-item " + (index === currentIndex ? "active" : "") }
onClick={ e => this.itemClick(index) }>
<span>{ item }</span>
</div>
)
})
}
</div>
)
}
itemClick(index) {
this.setState({
currentIndex: index
})
const { itemClick } = this.props
itemClick(index)
}
}
TabControl.propTypes = {
titles: propTypes.array.isRequired
}
style.css
.tab-control {
display: flex;
height: 44px;
line-height: 44px;
}
.tab-item {
flex: 1;
text-align: center;
font-weight: 700;
}
.tab-item.active {
color: red;
}
.tab-item.active span {
padding: 5px 8px;
border-bottom: 3px solid red;
}