Tabs 仅在第一次激活时挂载 Tab 内容 [英] Tabs only mount Tab content on the first time it becomes active

查看:89
本文介绍了Tabs 仅在第一次激活时挂载 Tab 内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在第一次激活时加载标签内容,之后内容保留在 DOM 中

I would like to load the tab content only on the first time it becomes active, after that the content stays in the DOM

这就是我所拥有的

  <Tabs defaultActiveKey={1} animation={false} id="my-tabs" mountOnEnter unmountOnExit>
    <Tab eventKey={1}>
      <div>content1</div>
    </Tab>
    <Tab eventKey={2}>
      <div>content1</div>
    </Tab>
  </Tabs>

它工作正常,但切换选项卡之间存在延迟,因为我拥有的内容非常大,我只想在选项卡第一次激活时呈现一次.

it works fine, but there is a lag between switching tabs, since the content I have is quite large and I would like to render it only once, on the first time the tab becomes active.

有没有办法做到这一点?我正在使用 react-bootstrap 0.30.10

Is there a way to achieve that? I'm using react-bootstrap 0.30.10

推荐答案

更新:

显然 mountOnEnter 必须与 animation 一起使用,否则它将无法按预期工作.我进行了更改,现在可以正常工作

apparently mountOnEnter must be used with animation, otherwise it will not work as intended. I made the change and it works fine now

旧答案:

所以我想出了这个包装组件如下

so I have come up with this wrapping component as follow

class TabsLazyLoad extends Component {

  constructor(props) {
    super(props);
    this.state = this.getInitialState();
    this.handleSelect = this.handleSelect.bind(this);
  }

  getInitialState() {
    return {
      key: this.props.key || this.props.defaultActiveKey,
      rendered: [],
    };
  }

  addRenderedTab(key) {
    const newState = _.cloneDeep(this.state);
    newState.rendered.push(key);
    this.setState(newState);
  }

  handleSelect(key) {
    this.setState({ key });
  }

  render() {
    return (
      <Tabs activeKey={this.state.key} onSelect={this.handleSelect} {...this.props}>
        {_.map(this.props.children, (tabComponent) => {
          if (_.includes(this.state.rendered, tabComponent.props.eventKey)) {
            return tabComponent;
          }
          if (tabComponent.props.eventKey === this.state.key) {
            this.addRenderedTab(this.state.key);
          }

          // if it's not rendered, return an empty tab
          const emptyTab = _.cloneDeep(tabComponent);
          emptyTab.props.children = null;
          return emptyTab;
        })}
      </Tabs>
    );
  }
}

TabsLazyLoad.propTypes = Tabs.propTypes;

它似乎工作正常,但我认为这有点hacky,但这是我现在能想到的最好的方法.

It seems to be working fine, but I reckon this is a bit hacky, but it's the best I can come up with for now.

这篇关于Tabs 仅在第一次激活时挂载 Tab 内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆