【问题标题】:How to lazy mount Material UI tab panels or to know when a tab panel is visible?如何延迟安装 Material UI 选项卡面板或知道选项卡面板何时可见?
【发布时间】:2019-08-12 17:29:44
【问题描述】:

我正在使用 Material UI 选项卡在三个 TabPanel 之间进行选择。具体来说,我使用的是Simple Tabs Example

我的第二个选项卡中的组件需要访问elem.offsetHeightelem.getClientRects() 等字段和方法来调整布局。不幸的是,在面板中的组件显示之前,这些基于显示的东西是零或空的。所有面板都会立即安装,但第二个面板在安装时不可见,因此当我在安装期间尝试运行它们时,我的布局调整不起作用。

我认为我需要的是两件事之一:

  1. 一些延迟加载标签面板内容的方法。 (这个解决方案可能是最好的,因为第二个和第三个面板需要网络调用,并且在需要面板之前进行这样的调用是没有意义的。)

  2. 某种方式可以知道面板的内容何时最终显示,以便代码可以触发布局调整。

另一种解决方案是设置一个超时来定期检查(比如每 100 毫秒)elem.getClientRects() 是否生成一个包含任何元素的列表,但这似乎相当 hacky。


附录

很抱歉,我的书面描述不够清晰。在我的SimpleTabs 组件中:

  <TabPanel value={value} index={0}>
    <About/>
  </TabPanel>
  <TabPanel value={value} index={1}>
    <ByRossPage/>
  </TabPanel>
  <TabPanel value={value} index={2}>
    <ByChapter/>
  </TabPanel>

&lt;ByRossPage/&gt; 组件包含访问elem.offsetHeightelem.getClientRects()getPage() 方法。该方法从组件的构造函数中调用。

【问题讨论】:

  • 你能告诉我们一些你的代码吗?

标签: reactjs material-ui


【解决方案1】:

我想出了如何让 TabPanel 的内容延迟加载。我这样修改了 TabPanel 功能组件:

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <Typography
      component="div"
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
    >
      <Box p={3}>{value === index && children}</Box>
    </Typography>
  );
}

唯一改变的是这一行:

 <Box p={3}>{value === index && children}</Box>

原来是这样的

<Box p={3}>{children}</Box>

【讨论】:

    【解决方案2】:

    你可以通过修改 TabPanel 来做到这一点

    function TabPanel(props: TabPanelProps) {
      const { children, value, index, ...other } = props;
      const panel = React.useRef();
      // this will run after the component mounted.
      React.useEffect(() => { 
         console.log(panel.current.getClientRects());
      }, []);
      return (
        <div ref={panel}>
        <Typography
          component="div"
          role="tabpanel"
          hidden={value !== index}
          id={`simple-tabpanel-${index}`}
          aria-labelledby={`simple-tab-${index}`}
          {...other}
        >
          <Box p={3}>{children}</Box>
        </Typography>
        </div>
      );
    }
    

    【讨论】:

    • 很抱歉我写的不够清楚。我正在尝试从 TabPanel 内部的组件访问getClientRects(),而不是从 TabPanel 本身。
    • 此外,所有三个面板都在开始时安装,无论给定的 TabPanel 是否可见。
    猜你喜欢
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    相关资源
    最近更新 更多