基礎-React實現tab切換

nav.jsx如下: 

import React from 'react';
import "./css/nav.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>
                <div className="tab_title_warp">
                    {
                        React.Children.map(this.props.children, (element, index) => { //React.Children.map 會遍歷任何類型的this.props.children
                            return (
                                <div onClick={() => {
                                    this.setState({
                                        currentIndex: index
                                    })
                                }}
                                     className={this.check_title_index(index)}>
                                    {element.props.name}
                                </div>
                            )
                        })
                    }
                </div>
                <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;

index.js

import TabsControl from './nav'

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('root'));

 React我剛開始學習,這個例子是參考學習別人的:原文地址http://www.cnblogs.com/tianheila/p/5170330.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章