React组件之间通信(tab栏切换)

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;
}

最终实现效果
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值