ReactJs导航栏的实现

  • getInitialState 方法用于定义初始状态,使用this.state.属性的方式读取状 态值。
  • 当状态发生变化是就会调用render方法重新渲染。
  • 通过this.setState()的方法改变状态值。
  • 通过this.props.属性的方式获取父组件传递给子组件的属性或者方法。
  • 子组件是不能直接修改父组件的状态,因此父组件传递给子组件一个方法,子组件想要修改状态时,只需调用父组件传过来的方法改变父组件的状态。
  • 每一个子组件之间都是相互独立的,当一个组件得到一个改变是另一个组件状态的命令, 是无法传递命令,因此需要将这个状态交给他们共同的父组件,让父组件传递命令。

Index 标记的是那一栏被选中的状态,当为0是表示没有点击什么一栏。onhandleClick 方法是改变状态的方法。

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组件 是有多个Bar组件组成,Bar组件的个数是由父组件传递的msg数据确定的,通过时候用Map栏循环遍历生成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(){
// 当选中的值和父组件相同时,Index的值就是那一栏被选中
//当鼠标以上是状态为1,离开为零通过Index和IsSlecct的值确定每一栏的状态
        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>
        );
    }
})```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容