美文网首页
react 标签页tabs

react 标签页tabs

作者: 半夜成仙 | 来源:发表于2020-07-14 14:14 被阅读0次

实现原理:定义一个公共的数组 定义点击事件 使用map 遍历数组

以下形式的数组:键名可自己取。
要定义一个唯一值而且必须是字符串类型,作用是给遍历的标签绑定唯一的key值
const panes = [
      { title: 'Tab 1', content: 'Content of Tab Pane 1', key: '1' },
      { title: 'Tab 2', content: 'Content of Tab Pane 2', key: '2' },
    ];


遍历数组,
注:TabPane 的key属性的值必须是字符串
 {this.state.panes.map(pane => (
            <TabPane tab={pane.title} key={pane.key}>
              {pane.content}
            </TabPane>
          ))}


addTabs组件

import React from 'react'
import {Button} from "antd";
import {observer} from 'mobx-react'
import tabsStore from "../../store/TabsStore";  //引入状态管理文件 局部引入
import emitter from '../../util/event'   //引入 event   作用:主要实现兄弟之间传值
@observer
class AddTabs extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      panes:tabsStore.getPane().panes, //初始 tabs
    };
  }
  add = (/*可以如想要传入的实参*/) => {
    var key = JSON.stringify(parseInt(this.state.panes[parseInt(this.state.panes.length)-1].key)+1)  // key值是panes数组最后一项的key键的值加一
    tabsStore.addTabs('导航'+key,'/login'+key,key) // 使用 状态管理的方法
    emitter.emit('key', key)   //兄弟之间传值  传入最新的activeKey值
  };

/*例子:
 add = (tit,url,id) => {
   // 判断标签页是否存在
   // 通过对象id值得判断
    
    if(tabsStore.checkId(id)){
//判断为true
      this.props.history.push(tabsStore.getUrl(id,tabsStore.panes))   通过当前id 获取url 并跳转到当前获取的url
      emitter.emit('key', tabsStore.getKey(id))  通过id 获取显示的key值 传给TabsT组件
      sessionStorage.setItem('activeKey',tabsStore.getKey(id))  刷新时使用,
     
    }else{
        标签页不存在添加到panes数组
      var key = JSON.stringify(parseInt(this.state.panes[parseInt(this.state.panes.length)-1].key)+1)  // 当前key值是panes数组最后一项对象的key键的值加一
      tabsStore.addTabs(tit,url,id,key) // 使用 状态管理的方法
      emitter.emit('key', key)   //兄弟之间传值 发给TabsT组件
      sessionStorage.setItem('activeKey',key)   刷新 
    } */


  render() {
    return (
        <div style={{ marginBottom: 16 }}>
          <Button onClick={this.add}>ADD</Button>
        </div>
    )
  }
}
export {AddTabs as default}

TabsT组件

import React from 'react';
import { Tabs } from 'antd';
import {observer} from 'mobx-react'
import tabsStore from "../../store/TabsStore";  //引入状态管理文件 局部引入
import emitter from '../../util/event'   //引入 event
import RouterList from '../../component/PrivateRouter'
const { TabPane } = Tabs;
@observer
class TabsT extends React.Component {
  constructor(props) {
    super(props);
// 接收AddTabs组件传的值
    emitter.on('key', opt => {
      // 参数
      this.setState({
        activeKey: opt
      })
    })
//初始数据
    this.state = {
      panes:tabsStore.getPane().panes,
      activeKey:sessionStorage.getItem('activeKey') || tabsStore.getKey().activeKey,
    };
  }
//点击对应的标签页的显示
  onChange =( activeKey) => {
    tabsStore.setActiveTabs(activeKey)
    this.setState({ activeKey });
 this.props.history.push(tabsStore.getKeyUrl(activeKey,tabsStore.panes))
  };
  // 叉掉标签页
  onEdit = (targetKey) => {
    this.remove(targetKey)
  };
//移除
  remove = (targetKey) => {

    new Promise((resolve)=>{
       //判断移除项是否是激活状态
    // 存在
      if (this.state.activeKey==targetKey){
        let index = tabsStore.getIndex(targetKey)
        // 删除的上一个数组对象的key
        let key = tabsStore.panes[index-1].key
       this.onChange(key)
        resolve()
      }else{
        resolve()
      }
    }).then(()=>{
      tabsStore.removeTabs(targetKey)
    })
  };

  render() {
    return (
        <div>
          <Tabs
              hideAdd
              onChange={this.onChange}
              activeKey={this.state.activeKey}
              type="editable-card"
              onEdit={this.onEdit}
          >
            {this.state.panes.map(pane => (
                <TabPane tab={pane.title} key={pane.key}>
                 {内容显示}
                </TabPane>
            ))}
          </Tabs>
        </div>
    )
  }
}

export {TabsT as default}

tabsStore ----mobx


import { observable, action } from 'mobx'
class TabsStore  {
  

  @observable  panes = JSON.parse(sessionStorage.getItem('panes')) || [
    { title: '会员信息统计',url:'/index/sysIndex/userTotal',id:11, key: '1' },
  ];//初始标签显示几个
  @observable  activeKey = this.panes[0].key//激活的 key值

  @action
  getPane(){
    return {
      panes:this.panes,
    }
  }
  // 获取激活的key
  getKey(){
    return  {
      activeKey:this.activeKey
    }
  }

  // 添加标签
  addTabs=(tit,url,id,key)=>{
      this.panes.push({ title: tit, url: url,id:id, key: key });
      this.activeKey = key
      sessionStorage.setItem('panes',JSON.stringify(this.panes))//数组

  }

  // 点击标签页显示
  setActiveTabs(activeIndex){
    this.activeKey = activeIndex
  }

// 判断panes中是否存在id
checkId(id,arr){
  let istrue = false
  for(let i=0;i<this.panes.length;i++){
    if(id == this.panes[i].id){
      istrue = true
    }
  }
  return istrue
}
  // 根据对象id获取url
  getUrl(id,arr){
    let url=''
    for(let i=0;i<arr.length;i++){
      if(id == arr[i].id){
        url = arr[i].url
      }
    }
    return url

  }
// 通过id获取key
getKey(id){
  let key='';
  for(let i=0;i<this.panes.length;i++){
    if(id == this.panes[i].id){
      key = this.panes[i].key
    }
  }
  return key
}

// 通过key获取url
  getKeyUrl(key,arr){
    let url=''
    for(let i=0;i<arr.length;i++){
      if(key == arr[i].key){
        url = arr[i].url
      }
    }
    return url

  }

  // 通过key获取下标
  getIndex(key){
    let index='';
    for(let i=0;i<this.panes.length;i++){
      if(key == this.panes[i].key){
        index = i;
      }
    }
    return index
  }


  // 移除标签
  // 从数组中移除数据
  removeTabs(targetKey){
    new Promise((resolve)=>{
      this.panes.forEach((pane, i) => {
        if (pane.key==targetKey){
          if (this.panes.length>1){
            if (i==0){
              this.panes.splice(i,1)
              resolve()
            }else {
              this.panes.splice(i,1)
              resolve()
            }
          }
        }
      });
     
    }).then(()=>{
      sessionStorage.setItem('panes',JSON.stringify(this.panes))//数组

    })

   
  }
}

const tabsStore = new TabsStore;

export default  tabsStore;

相关文章

网友评论

      本文标题:react 标签页tabs

      本文链接:https://www.haomeiwen.com/subject/ydsxhktx.html