基于React的Tab组件

本文介绍了一个基于 React 实现的 Tabs 组件,该组件通过 TabPane 子组件展示不同的面板内容,并通过点击标题来切换显示的面板。文章提供了完整的代码示例,包括如何渲染标题和内容,以及如何设置激活状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于React的Tab组件

Tabs

renderHeader = () => {
    return React.Children.map( this.props.children , (element,index) => {
      const activeStyle = element.key === this.state.activeKey ? "activeTitle" : null;
      return (
          <span
              onClick={() => {
                this.setState({
                  activeKey: element.key
                })
              }}
              className={classnames("title", activeStyle)}
          >
            {element.props.title}
          </span>
      )
    })
  }

  renderContent = () => {
    return React.Children.map( this.props.children , (element,index) => {
      if (element.key === this.state.activeKey) {
        return (<div>{element.props.children}</div>)
      }
    })
  }

  render() {
    return (
        <div className="container">
          <div className="titleContainer">{this.renderHeader()}</div>
          <div className="contentContainer">{this.renderContent()}</div>
        </div>
    )
  }

TabPane

render() {
    return (
        <div>
          <div>{this.props.title}</div>
          <div>{this.props.children}</div>
        </div>
    )
  }

调用

render() {
    return (
        <div>
          <Tabs activeKey="1">
            <TabPane title="title1" key="1">content1</TabPane>
            <TabPane title="title2" key="2">content2</TabPane>
          </Tabs>
        </div>
    )
  }

转载于:https://www.cnblogs.com/simply-yu/p/9425112.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值