【问题标题】:Collapse one AppBar and show another AppBar at the same time on scroll in Material UI在 Material UI 中滚动时折叠一个 AppBar 并同时显示另一个 AppBar
【发布时间】:2020-09-06 21:02:45
【问题描述】:

我有Header.js 组件。在里面,我有两个 AppBar,第一个 AppBar 是粘性的,第二个不是。默认情况下,只显示第二个 AppBar。当我们滚动时,我希望第二个 AppBar 折叠,第一个 AppBar 显示在屏幕顶部。

我在 Material-ui 文档 here 中看到了 useScrollTrigger(),但它只显示在滚动时隐藏 AppBar。

// Header.js
import React from "react";
import { AppBar, Toolbar, Typography } from "@material-ui/core";

export default function Header() {
  return (
    <>
    <AppBar position="static">
      <Toolbar>
        <Typography variant="h6">First AppBar</Typography>
      </Toolbar>
    </AppBar>
    <AppBar position="static">
      <Toolbar>
        <Typography variant="h6">Second AppBar</Typography>
      </Toolbar>
    </AppBar>
    </>
  );
}

这是我的沙盒link

【问题讨论】:

    标签: javascript css reactjs material-ui appbar


    【解决方案1】:

    这段代码看起来像你想要的那样运行。我用了material-ui demo

    import React from "react";
    import { AppBar, Toolbar, Typography } from "@material-ui/core";
    import useScrollTrigger from '@material-ui/core/useScrollTrigger';
    import Slide from '@material-ui/core/Slide';
    
    function HideOnScroll(props) {
      const { children, window } = props;
      const trigger = useScrollTrigger({ target: window ? window() : undefined });
    
      return (
        <Slide appear={false} direction="down" in={!trigger}>
          {children}
        </Slide>
      );
    }
    
    function ElevationScroll(props) {
      const { children, window } = props;
      const trigger = useScrollTrigger({
        disableHysteresis: true,
        threshold: 0,
        target: window ? window() : undefined,
      });
    
      return React.cloneElement(children, {
        elevation: trigger ? 4 : 0,
      });
    }
    
    
    export default function Header(props) {
      return (
        <>
          <ElevationScroll  {...props}>
          <AppBar>
            <Toolbar>
              <Typography variant="h6">First AppBar</Typography>
            </Toolbar>
          </AppBar>
          </ElevationScroll >
          {/* second appbar */}
          <HideOnScroll {...props}>
          <AppBar>
            <Toolbar>
              <Typography variant="h6">Second AppBar</Typography>
            </Toolbar>
          </AppBar>
          </HideOnScroll>
        </>
      );
    }
    

    【讨论】:

    • 您好,我将您的代码复制到我的沙箱,但它似乎没有按我的预期工作。它从一开始就显示了两个应用栏,当我滚动时,我的第二个应用栏崩溃了,让我的第一个应用栏显示出来。我不希望从一开始就显示第一个应用程序栏(我只想要第二个应用程序栏),但是当我滚动时,第二个应用程序栏必须折叠并显示第一个应用程序栏。基本上,如果我们滚动,第一个 appbar 会取代第二个 appbar。
    • 然后你可以尝试提升选项。我已经编辑了代码。最初只显示第二个应用栏,滚动时隐藏并显示第一个应用栏。
    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2019-11-29
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多