index.js
渲染app组件
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(<App />, document.getElementById('root'));
app.js
import React, { Component } from 'react';
import TabControl from './TabControl';
export default class App extends Component {
constructor(props) {
super(props);
// 不经常更改的数据存放到state外面
this.titles = ['新款', '精选', '流行'];
this.state = {
currendTitle: '新款',
};
}
render() {
const { currendTitle } = this.state;
return (
<div>
<TabControl
itemClick={(index) => this.itemClick(index)}
titles={this.titles}
/>
<h2>{currendTitle}</h2>
</div>
);
}
itemClick(index) {
this.setState({
currendTitle: this.titles[index],
});
}
}
TabControl组件
import React, { Component } from 'react';
export default class TabControl extends Component {
constructor(props) {
super(props);
this.state = {
currentIndex: 0,
};
}
render() {
const { titles } = this.props;
return (
<div className="tab-control">
{titles.map((item, index) => {
return (
<div
key={index}
className={
'tab-item' +
' ' +
(index === this.state.currentIndex && 'active')
}
onClick={(e) => this.indexChange(index)}
>
<span>{item}</span>
</div>
);
})}
</div>
);
}
indexChange(index) {
this.setState({
currentIndex: index,
});
const { itemClick } = this.props;
itemClick(index);
}
}
index.css
.tab-control {
display: flex;
height: 44px;
line-height: 44px;
}
.tab-item {
flex: 1;
text-align: center;
}
.tab-item span {
padding: 2px 10px;
}
.tab-item.active {
color: red;
}
.tab-item.active span {
border-bottom: 2px solid #f00;
}
最终实现效果