react实现的tab切换组件
这几天在学习react框架,组件化的思想真的很酷。下面总结一下一个简单react tab切换组件的实现过程。
项目源码:react-tab
组件核心代码
import React from "react" import "../css/style.css" class TabsControl extends React.Component{ constructor( ){ super( ) this.state = { currentIndex : 0 } } check_title_index( index ){ return index === this.state.currentIndex ? "tab_title active" : "tab_title" } check_item_index( index ){ return index === this.state.currentIndex ? "tab_item show" : "tab_item" } render( ){ let _this = this return( <div> { /* 动态生成Tab导航 */ } <div className="tab_title_wrap"> { React.Children.map( this.props.children , ( element,index ) => { return( <div onClick={ ( ) => { this.setState({ currentIndex : index }) } } className={ this.check_title_index( index ) }>{ element.props.name }</div> ) }) } </div> { /* Tab内容区域 */ } <div className="tab_item_wrap"> { React.Children.map(this.props.children,( element,index )=>{ return( <div className={ this.check_item_index( index ) }>{ element }</div> ) }) } </div> </div> ) } } export default TabsControl
组件使用
import React from "react" import ReactDOM from "react-dom" import TabsControl from "./react_tab.jsx" class TabComponent extends React.Component{ render( ){ return( <div className="container"> <TabsControl> <div name = "first"> 第一帧 </div> <div name = "second"> 第二帧 </div> <div name = "third"> 第三帧 </div> </TabsControl> </div> ) } } ReactDOM.render(<TabComponent/>,document.getElementById("app"))
实现思路:
在使用<TabsControl/>组件时会传入任意数量的div,即为切换组件的主要内容帧,在组件内部通过 this.props.children 获取到主要内容帧,并且动态生成相应数量的tab_title,再对标题区和内容区设置合适的className,以控制标题区的颜色切换和内容区域的显示和隐藏,组件通过 state 存放 index 来记忆被点击的区域,并且每一个标题区域都有绑定一个 click 处理方法,每一次点击都会更新 state 的 index 值,组件会自动调用 this.render 方法重新渲染视图,上面说到的 className 的设置规则也是借由index值来实现的 => 当标题区域或者内容区域其对应的索引值与 state 中的 index 相同的时候,给它们添加具有特殊的即动态标示的className,使得当前被点击标题高亮以及对应的内容帧显现。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?