7-组件通信案例

 

 

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值