react better-scroll 编写类似手机chrome的header显示隐藏效果

关键代码

const H = 50; // header的高度
const H2 = H / 2;
let cy = 0;

class Home extends Component {
  @observable top = 0;
  @observable ms = 0;

  onScroll = ({ y }) => {
    let scrollLength = Math.abs(y - cy);

    if (y < cy) {
      l("paeg up");
      if (this.top >= -H) {
        const newTop = this.top - scrollLength;
        this.top = Math.max(newTop, -H);
      }
    } else if (y > cy) {
      // l("page down");
      if (this.top <= 0) {
        let newTop = this.top + scrollLength;
        this.top = Math.min(newTop, 0);
      }
    } else {
      // l("没动");
    }

    if (cy !== y) cy = y; // 保存这一次的值,在下一次作比较
  };

  onScrollEnd = ({ y }) => {
    const top = Math.abs(this.top);
    this.ms = 200;
    if (top <= H2) {
      l("show");
      this.top = 0;
    } else {
      l("hide");
      this.top = -H;
    }
    this.ms = 0;
  };

  render() {
    const { classes } = this.props;
    return (
      <div class={classes.root}>
        {/* hedaer */}
        <HomeHeader top={this.top} ms={this.ms} />

        <div className={classes.wraper}>
          <Scroll
            onScroll={this.onScroll}
            onScrollEnd={this.onScrollEnd}
            bounce={false}
          >
            <div> ... </div>
          </Scroll>
        </div>
      </div>
    );
  }
}


class HomeHeader extends Component {
  render() {
    const { top, ms } = this.props;
    return (
      <AppBar
        color="inherit"
        position="fixed"
        style={{
          transition: `transform ${ms}ms ease`,
          transform: `translateY(${top}px)`,
        }}
      > ... </AppBar>
    );
  }
}

转载于:https://www.cnblogs.com/ajanuw/p/10156586.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值