本文不採用ES6寫,用ES5寫方便初學者學習
實現原理很簡單,根據state的變化實現改變class
那麼咱們開始吧...react
<TabControl>//父組件 <Spannav />//子組件,標籤頁的標題 <Contentnav />//子組件,對應的內容 </TabControl>
var React = require('react'); var ReactDOM = require('react-dom'); var TabControl = React.createClass({ getInitialState: function(){ return { currentIndex:0, //默認當前的索引值 tabnav:[{title:'標題一', content:'內容一'}, {title:'標題二', content:'內容二'}, {title:'標題三', content:'內容三'} ]//數據 } }, handleClick:function(index){ this.setState({ currentIndex:index //由map循環傳遞的index }); }, render:function(){ //循環出3個標籤 //注意map會改變this指向,用bind修正this指向 var navmap = this.state.tabnav.map(function(arr, index){ //判斷index是否和this.state.currentIndex相等,相等就加上active的class var cn = index === this.state.currentIndex ? 'active' : ''; //this.handleClick.bind(this,index)這裏用bind主要是用來傳遞index的值,這樣咱們就可動態給currentIndex賦值並對應索引值 return ( <Spannav active={cn} handleClick={this.handleClick.bind(this,index)} key={index} titles={arr.title} />) }.bind(this)) ; //循環出3個內容,原理同上 var conmap = this.state.tabnav.map(function(arr, index){ var cn = index === this.state.currentIndex ? 'active' : ''; return ( <Contentnav active={cn} key={index} con={arr.content} />) }.bind(this)); return ( <div> {//輸出} {navmap} {conmap} </div> ) } });
var Spannav = React.createClass({ render:function(){ return ( {//子組件接收父組件傳來的值要用this.props.xxx} <span className={this.props.active} onClick={this.props.handleClick}>{this.props.titles}</span> ) } }); var Contentnav = React.createClass({ render: function() { return ( <div className={this.props.active}>{this.props.con}</div> ) } });
ReactDOM.render( <TabControl />, document.getElementById('app') );