React 基础巩固(十九)——组件化开发(三)
组件通信小案例
- Main.jsx
import React, { Component } from "react";
import TabControl from "./TabControl";
export class Main extends Component {
constructor() {
super();
this.state = {
titles: ["流行", "新款", "精选"],
tabIndex: 0,
};
}
tabClick(index) {
this.setState({
tabIndex: index,
});
}
render() {
const { titles, tabIndex } = this.state;
return (
<div>
<TabControl titles={titles} tabClick={(i) => this.tabClick(i)} />
<h1>{titles[tabIndex]}</h1>
</div>
);
}
}
export default Main;
- TabControl/index.jsx
import React, { Component } from "react";
import "./style.css";
export class TabControl extends Component {
constructor() {
super();
this.state = {
currentIndex: 0,
};
}
itemClick(index) {
this.setState({ currentIndex: index });
this.props.tabClick(index);
}
render() {
const { titles } = this.props;
const { currentIndex } = this.state;
return (
<div className="tab-control">
{titles.map((item, index) => {
return (
<div
className={`item ${currentIndex === index ? "active" : ""}`}
key={item}
onClick={(e) => this.itemClick(index)}
>
<span className="text">{item}</span>
</div>
);
})}
</div>
);
}
}
export default TabControl;
- TabControl/style.css
.tab-control {
display: flex;
align-items: center;
height: 40px;
text-align: center;
}
.tab-control .item {
flex: 1;
}
.tab-control .item.active {
color: red;
}
.tab-control .item.active .text {
padding: 3px;
border-bottom: 3px solid red;
}
文章来源地址https://www.toymoban.com/news/detail-549292.html
文章来源:https://www.toymoban.com/news/detail-549292.html
到了这里,关于【前端知识】React 基础巩固(十九)——组件化开发(三)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!