Ant 有条件地设计 goTotab 函数

问题描述

我正在使用 ant design mobile,我有条件地切换选项卡。

我有两个选项卡,一个是 topCategorytab 另一个是 subCategory 选项卡我想实现,当用户单击 topCategoryTab 之一时,应立即将 subCategory 选项卡的 activetab 重置为 0 。

这是我试过的:

 <Tabs
            tabBarPosition="bottom"
            onTabClick={(tab,index) => {
              this.getRestaurantItems(
                tab.product_category_id,this.state.currentSubCatId
              );
              this.findSubCategories(tab.product_category_id);

              this.setState({
                currentTopCatId: tab.product_category_id,subCatTabInitialTab: 0,});
            }}
            tabs={this.state.tabs}
            initialPage={0}
            renderTabBar={(props) => <Tabs.DefaultTabBar {...props} page={4} />}
          />
          <WhiteSpace />

          <Tabs
            onTabClick={(tab,index) => {
              this.setState({
                currentSubCatId: tab.subCatId,});
              this.getRestaurantItems(this.state.currentTopCatId,tab.subCatId);
              console.log(
                "state sub category id veee top cat id",this.state.currentTopCatId,tab.subCatId
              );
            }}
            tabs={this.state.subCategories}
            initialPage={0}
            goToTab={this.state.subCatTabInitialTab}
            renderTabBar={(props) => <Tabs.DefaultTabBar {...props} page={3} />}
          >
            {this.renderContent}
          </Tabs>

在文档中他们说的是:goToTab 调用这个函数来切换 Tab (index: number) => boolean true

但我真的不明白这个 goToTab 函数用法

解决方法

我为以后会遇到此类问题的人做了一个codepen的demo,非常符合我的要求

state = {
    tabIndex:0,}
  renderContent = tab =>
    (<div style={{ display: 'flex',alignItems: 'center',justifyContent: 'center',height: '150px',backgroundColor: '#fff' }}>
      <p>Content of {tab.title}</p>
    </div>);
//goToTab   call this function to switch Tab    (index: number) => boolean
  render() {
    const tabs = [
      { title: '1st Tab' },{ title: '2nd Tab' },{ title: '3rd Tab' },{ title: '4th Tab' },{ title: '5th Tab' },{ title: '6th Tab' },{ title: '7th Tab' },{ title: '8th Tab' },{ title: '9th Tab' },];
    

    return (
      <div>
        <WhiteSpace />
       <Tabs onTabClick={(tab,index)=>{
          this.setState({
            tabIndex:0
          })
    }} tabs={tabs} renderTabBar={props => <Tabs.DefaultTabBar {...props} page={3} />}>
          {this.renderContent}
        </Tabs>
        <Tabs onTabClick={(tab,index) =>{
          this.setState({
          tabIndex : index
        })
        }
        }
        page={this.state.tabIndex || 0} tabs={tabs} renderTabBar={props => <Tabs.DefaultTabBar {...props} page={3} />}>
          {this.renderContent}
        </Tabs>
        <WhiteSpace />
      </div>

使用 tabIndex 状态来跟踪子选项卡的当前位置和插入的 topTabs setState -> tabIndex: 0 用于重置 subTabs 索引

并实现了我自己的代码。 这是演示:https://codepen.io/dnnzz/pen/yLbLyqb