forked from mheiber/react-tabs-component
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Tabs.js
86 lines (74 loc) · 1.98 KB
/
Tabs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
var React=require('react/addons');
var getChildrenArray=function(context){
var children=[];
React.Children.forEach(context.props.children,function(child){
children.push(child);
});
return children;
};
var noop=function(){};
var Tabs=React.createClass({
propTypes:{
defaultTabNum:React.PropTypes.number,
tabNames:React.PropTypes.array.isRequired,
willChange:React.PropTypes.func,
didChange:React.PropTypes.func,
classPrefix:React.PropTypes.string
},
getDefaultProps:function(){
return {
defaultTabNum:0,
willChange:noop,
didChange:noop,
classPrefix:''
};
},
getInitialState:function(){
return {activeTabNum:this.props.defaultTabNum};
},
setActiveTabNum:function(num,callback){
this.setState({activeTabNum:num},callback);
},
getActiveTabNum:function(){
return this.state.activeTabNum;
},
_change:function(e){
var oldActiveTabNum=this.state.activeTabNum;
var newActiveTabNum=parseInt(e.target.getAttribute('data-tabnum'));
var allowChange=this.props.willChange(newActiveTabNum,oldActiveTabNum);
if (typeof allowChange !== 'undefined' && !allowChange){
return;
}
var callback=function(){
this.props.didChange(newActiveTabNum,oldActiveTabNum);
}.bind(this);
this.setActiveTabNum(newActiveTabNum,callback);
},
render:function(){
var children=getChildrenArray(this);
var activeTabContent=children[this.state.activeTabNum];
var classPrefix=this.props.classPrefix;
var tabClassName=classPrefix+'tab';
var activeTabClassName=tabClassName+' '+classPrefix+'active-tab';
var tabs=this.props.tabNames.map(function(tabName,tabNum){
var isActive= tabNum===this.state.activeTabNum;
return (
<span
key={'tab-'+tabNum}
className={isActive? activeTabClassName : tabClassName }
data-tabnum={tabNum}
onClick={this._change}
>
{tabName}
</span>
);
}.bind(this));
return (
<div>
<nav className={classPrefix+'tab-container'}>{tabs}</nav>
{activeTabContent}
</div>
);
}
});
module.exports=Tabs;