使用react完成标签切换

特点:直接把多个div映射为tab+div的形式

效果图
使用react完成标签切换_第1张图片
除了点击标签切换显示之外,还有个地方需要特别注意,切换后,title下面的边框要去掉,这样才与内容是一体的,很多案例都只是实现tab切换而已,参考浏览器的标签切换,页面和标题之间的border是要去掉的,这个地方的实现思路:content的边框大小是1px,那么让整个nav下沉1px,同时把当前的title的下边框设置为内容的背景色,这样子就挡住了内容的上边框,title和内容变成一个整体了。
tab切换,用react来实现是很简单的,点击title时,把state设置为对应的索引,如果内容的索引等于state,那么显示,否则不显示。

html


<html>
<head>
    <title>title>
head>
<body>
    <div id="container">div>
    <script type="text/javascript" src="bundle.js">script>
body>
html>

css

.tab-container{
    position: relative;
}
.nav-tab{
    display:table;
    width:800px;
    box-sizing: border-box;
    position: relative;
    top: 1px;
    border:1px solid #222;
    border-bottom:none;
}
.tab-title{
    display:table-cell;
    border-right:1px solid #222;
    height:2em;
    vertical-align: middle;
    text-align: center;
    cursor: pointer;
}
.tab-title:last-child{
    border-right:none;
}
.tab-content{
    display:none;
    width:800px;
    height:600px;
    border: 1px solid #222;
    box-sizing: border-box;
    background-color:#ddd;
}

.tab-title-shown{
    border-bottom: 1px solid #ddd;
}

.shown{
    display:block;
}

babel

import React from 'react';
import ReactDOM from 'react-dom';
require('../style/tab.scss');

class App extends React.Component{
    render(){
        return(
            
                
'red'>我是红色
'blue'>我是蓝色
'yellow'>我是黄色
'green'>我是绿色
) } } class TabController extends React.Component{ constructor(props){ super(props); this.state={ currentIndex:0 } } render(){ return( <div className='tab-container'> <div> {React.Children.map(this.props.children,(element,index)=>(<div className={this.addContentClass(index)}>{element}div>))} div> div> ) } addTitleClass(index){ return index==this.state.currentIndex?'tab-title tab-title-shown':'tab-title'; } addContentClass(index){ return index==this.state.currentIndex?'tab-content shown':'tab-content'; } changeTab(index){ this.setState({ currentIndex: index }) } } ReactDOM.render(,document.getElementById('container'));

参考资料:
https://segmentfault.com/a/1190000004200481

你可能感兴趣的:(react轮子)