這幾天在學習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,使得當前被點擊標題高亮以及對應的內容幀顯現。