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,使得当前被点击标题高亮以及对应的内容帧显现。

 

posted @ 2016-01-29 23:44  Levitt  阅读(22341)  评论(4编辑  收藏  举报