ReactJs導(dǎo)航欄的實(shí)現(xiàn)

  • getInitialState 方法用于定義初始狀態(tài),使用this.state.屬性的方式讀取狀 態(tài)值。
  • 當(dāng)狀態(tài)發(fā)生變化是就會(huì)調(diào)用render方法重新渲染。
  • 通過(guò)this.setState()的方法改變狀態(tài)值。
  • 通過(guò)this.props.屬性的方式獲取父組件傳遞給子組件的屬性或者方法。
  • 子組件是不能直接修改父組件的狀態(tài),因此父組件傳遞給子組件一個(gè)方法,子組件想要修改狀態(tài)時(shí),只需調(diào)用父組件傳過(guò)來(lái)的方法改變父組件的狀態(tài)。
  • 每一個(gè)子組件之間都是相互獨(dú)立的,當(dāng)一個(gè)組件得到一個(gè)改變是另一個(gè)組件狀態(tài)的命令, 是無(wú)法傳遞命令,因此需要將這個(gè)狀態(tài)交給他們共同的父組件,讓父組件傳遞命令。

Index 標(biāo)記的是那一欄被選中的狀態(tài),當(dāng)為0是表示沒(méi)有點(diǎn)擊什么一欄。onhandleClick 方法是改變狀態(tài)的方法。

var NavigationBar = React.createClass({

    getInitialState: function (){
       return {index:0}
   },
   onhandleClick : function(myIndex){
       this.setState({index:myIndex })
   },
   render(){
       return(
           <div className="nav">
              <BarList msg={this.props.msg} index={this.state.index} onhandleClick={this.onhandleClick}/>
          </div>);
       }
   }
))

BarList組件 是有多個(gè)Bar組件組成,Bar組件的個(gè)數(shù)是由父組件傳遞的msg數(shù)據(jù)確定的,通過(guò)時(shí)候用Map欄循環(huán)遍歷生成Bar組件

var BarList = React.createClass({
    render(){
        var index=this.props.index;
        var onhandleClick=this.props.onhandleClick;
        var bars = this.props.msg.map(function(m){
                return (<Bar icon={m.icon}  onhandleClick={onhandleClick} index={index} myIndex={m.index}
                name={m.name} />)       
         }
        );
        return(
        <div className="bars">{bars}</div>
        );
    }
});
var Bar = React.createClass({

    getInitialState:function(){
        return({isSelect:0})
    },
    handleClick:function(event){
     this.props.onhandleClick(this.props.myIndex)
    },
    onhandleOver:function(){  
        this.setState({isSelect:this.props.myIndex})
    },
    onhandleOut:function(){  
        this.setState({isSelect:0})
    },
    render(){
// 當(dāng)選中的值和父組件相同時(shí),Index的值就是那一欄被選中
//當(dāng)鼠標(biāo)以上是狀態(tài)為1,離開(kāi)為零通過(guò)Index和IsSlecct的值確定每一欄的狀態(tài)
        var style="bar"; 
        style=this.props.index===this.props.myIndex?"bar active":"bar";
        if(this.state.isSelect==0&&this.props.index!=this.props.myIndex)
            style="bar"
        if(this.state.isSelect!=0)
            style="bar active"
        return(
            <div className={style} 
             onMouseOver={this.onhandleOver} onMouseOut={this.onhandleOut}
             onClick={this.handleClick} >
                <a className="bara" >
                    <i></i>
                    {this.props.name}
                </a>
            </div>
        );
    }
})```
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容