如何使Material-ui-next中的AppBar组件对滚动事件做出反应

Put*_*San 5 javascript appbar reactjs material-ui

根据材料设计指南

滚动时,顶部应用程序栏可以以下方式进行转换:
-向上滚动隐藏顶部应用程序栏
-向下滚动显示顶部应用程序栏
当顶部应用程序栏滚动时,其在其他元素上方的高度变得明显。

在material-ui-next中是否有任何内置方法可以执行此操作,还是应将其视为新功能?您能否提示如何按照指南中所述实现AppBar组件的动画?

109*_*149 9

对于那些仍在寻找内置功能的人,可以material-ui.


use*_*265 8

据我所知,目前没有现成的解决方案。不过它很容易实现。这是订阅滚动事件并相应地隐藏或显示 AppBar 的片段:

const styles = {
  root: {
    flexGrow: 1,
  },
  show: {
    transform: 'translateY(0)',
    transition: 'transform .5s',
  },
  hide: {
    transform: 'translateY(-110%)',
    transition: 'transform .5s',
  },
};

class CollapsibleAppBar extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      shouldShow: null,
    };

    this.lastScroll = null;

    this.handleScroll = this.handleScroll.bind(this);
    // Alternatively, you can throttle scroll events to avoid
    // updating the state too often. Here using lodash.
    // this.handleScroll = _.throttle(this.handleScroll.bind(this), 100);
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll, { passive: true });
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  }

  handleScroll(evt) {
    const lastScroll = window.scrollY;

    if (lastScroll === this.lastScroll) {
      return;
    }

    const shouldShow = (this.lastScroll !== null) ?  (lastScroll < this.lastScroll) : null;

    if (shouldShow !== this.state.shouldShow) {
      this.setState((prevState, props) => ({
        ...prevState,
        shouldShow,
      }));
    }

    this.lastScroll = lastScroll;
  }

  render() {
    const { classes } = this.props;
    return (
        <AppBar
      position="fixed"
      color="default"
      className={
            `${classes.root} ${
              this.state.shouldShow === null ? '' : (
                this.state.shouldShow ? classes.show : classes.hide
              )
            }`
          }
    >
          <Toolbar>
            <Typography variant="title" color="inherit">
              Title
            </Typography>
          </Toolbar>
        </AppBar>
    );
  }
}

CollapsibleAppBar.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(CollapsibleAppBar);
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢!这是一个演示,它使用当前版本的 Material-UI (v1) 实现您的解决方案:https://codesandbox.io/s/4z56yl6rm4 (2认同)

ben*_*ich 7

在当前版本的Material-ui中,您可以简单地使用以下内容

import clsx from "clsx";
import useScrollTrigger from "@material-ui/core/useScrollTrigger";
const trigger = useScrollTrigger();

<AppBar className={trigger ? classes.show : classes.hide}>
</AppBar>
Run Code Online (Sandbox Code Playgroud)

https://material-ui.com/components/app-bar/#usescrolltrigger-options-trigger