顶部导航组件TabBar

顶部导航组件


顶部导航组件TabBar_第1张图片
IMG_3827.PNG

调用示例:

 //点击事件里要更改stata.activeKey来触发组件更新
  
  //tab页1
  

  //tab页2



选择事件:

tabChange({next: tabKey}){
  this.setState({activeKey: tabKey});
}

具体实现

export default class TabBar extends PureComponent {
  static Item = Item //子组件
  constructor(props) {
    super(props);
    //存储tab页id以及坐标,用于实现动画触发
    const map = new Map();
    props.children.forEach((child, index) => {
      //默认页面宽度为750,tabbar长度为80
      const length = 750 / props.children.length;
      const position = index * length + length / 2 - 42
      map.set(child.props.tabKey, position);
    })
    this.state = {
      map
    }
  }

  componentDidMount() {
    const left_new = this.state.map.get(this.props.activeKey)
    const dom = this.refs.border
    //初始动画渲染
    doTransition(dom, {transform: `translateX(${left_new + 80})`})
  }

  changeSelect(key) {//选择事件
    //获取点击tab页的坐标
    const left_new = this.state.map.get(key)
    const dom = this.refs.border
    //平移底部border
    doTransition(dom, {transform: `translateX(${left_new + 80})`}, null, () => {
    //回调
      this.props.onChange && this.props.onChange({next: key})
    })
  }

  getChild() {//获取子tab页
    //根据tab页id获取页面内容
    let child = this.props.children.find(child => {
    return child.props.tabKey == this.props.activeKey
  })



}

页面内容渲染

render(){
  let child = this.getChild()
  return (
    
      
        
          //渲染导航
          {this.props.children.map(obj => {
            const flag = obj.props.tabKey == this.props.activeKey
            return (
              
              //平分页面占比
              
                {obj.props.title}
                  
                {obj.props.nextTitle ? 
                  {obj.props.nextTitle} 
                  : null}
              
              
                
                  {!obj.props.total || 
                  (obj.props.total == 0 && !this.props.showZero) ? 
                    '' :
                    obj.props.total > 9999 ? 
                      `(9999+)` : `(${obj.props.total})`}
                
              
            )
          })}
        
        //底部border
        
          
        
      
      //渲染根据tabkey得到的子组件
      {child}
    )

}

子组件实现:

import {createElement, PureComponent, render} from 'rax';
import {View, Text} from 'nuke';
import style from "./style.less"
export default class TabBarItem extends PureComponent{
    constructor(props){
        super(props);
    }
    render(){
        return(
            
                {this.props.children}
            
        )
    }
}

你可能感兴趣的:(顶部导航组件TabBar)