Tab選項卡切換是個很常見也很簡單的小功能,用原生js和jq去寫的話可能不到20行代碼就搞定so easy。可是用react去實現就沒那麼容易了(是本身react比較菜)。因爲最近在從新學習react就試着寫了一個tab切換的小列子。還有多可優化的地方但願能拋磚引玉(簡單寫了點註釋)。javascript
html代碼css
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="app" ></div> <script src="./dist/js/bundle.js" ></script> </body> </html>
js代碼html
import React,{Component} from 'react'; import {render} from 'react-dom'; class Tab extends Component{ constructor(){ super() this.state = { list:['導航一','導航二','導航三'], content:[ {item:'內容一'}, {item:'內容二'}, {item:'內容三'} ], current:0 } } handleClick(index){ this.setState({ current:index }); } currentClass(index){ return this.state.current === index ? 'current' : ''; } contentClass(index){ return this.state.current === index ? 'active' : ''; } render(){ return( <div id="outer" > <ul id="tab" > //經過props的形式傳遞數據和方法給子組件 //::this es7的語法詳見https://github.com/tc39/proposal-bind-operator { this.state.list.map( (val,index ) => { return (<List currentClass={::this.currentClass} handleClick={::this.handleClick} val={val} key={index} index={index} /> ) }) } </ul> <div id="content" > { this.state.content.map( ( val,index ) => { return ( <Content key={index} val={val.item} index={index} contentClass={::this.contentClass } /> ) })} </div> </div> ) } } class List extends Component{ handleClick(){ //調用父組件的方法 將邏輯處理交給父組件 this.props.handleClick(this.props.index); } render(){ return( <li className={this.props.currentClass(this.props.index)} onClick={::this.handleClick} >{this.props.val}</li> ) } } class Content extends Component{ render(){ return( <div className={this.props.contentClass(this.props.index)} >{ this.props.val }</div> ) } } render( <Tab/>,document.querySelector("#app") );
CSS代碼(sass)java
body,ul,li{ margin:0;padding:0; } body{ font:12px/1.5 Tahoma; } #outer{ width:450px; margin:10px auto; #tab{ overflow:hidden; background:#000; border:1px solid #000; li { float:left;color:#fff;height:30px; cursor:pointer;line-height:30px; list-style:none;padding:0 20px; } .current{ color:#000;background:#ccc; } } #content{ border:1px solid #000; border-top-width:0; height:300px; >div{ display:none; } .active{ display:block } } }
完整例子能夠移動到個人github上 react-tabreact