Taro抽屉动画

使用组件
<Consult consultHeight={consultHeight} />
index.jsx

import React, { useState, useEffect } from "react"
import Taro from "@tarojs/taro"
import { View, Image, ScrollView } from "@tarojs/components"
import { AtTabs, AtTabsPane, AtLoadMore } from "taro-ui"
import defaultIcon from "@images/ic_default.png"
import chuancai from "@images/top/ic_chuancai.svg"
import jiangzhecai from "@images/top/ic_jiangzhecai.svg"
import recommend from "@images/top/ic_recommend.svg"
import Http from "@/utils/http"
import { getPageHeight } from "@/utils/index"
import "./index.scss"

var touchStartX = 0 //触摸时的原点
var touchStartY = 0 //触摸时的原点
var time = 0 // 时间记录,用于滑动时且时间小于1s则执行左右滑动
var interval = "" // 记录/清理时间记录
var touchEndX = 0 // x轴方向移动的距离
var touchEndY = 0 // y轴方向移动的距离
var topHeight = 0
export default function Consult({ consultHeight }) {
  const [tabList, setTabList] = useState([{ key: "top", title: "热门餐厅" }])
  const [currentTab, setTabCurrent] = useState(0) //当前tab
  const [scrollMove, setScrollMove] = useState(0) //默认0向下1向上2
  const [currentLocation, setcCurrentLocation] = useState("END") //当前热门餐厅card位置
  const [restaList, setRestaList] = useState([])
  const [pageData, setPageData] = useState({
    current: 0,
    pageSize: 10,
    total: 0,
  })
  const [loadStatus, setLoadStatus] = useState("more")
  const [animationData, setAnimationData] = useState({})
  const [criticalValue, setVriticalValue] = useState(120)
  const duration = 500,
    animation = Taro.createAnimation({
      duration: 500,
      timingFunction: "ease",
    })

  const handleClick = c => {
    setTabCurrent(c)
    getRestaurantList({ typeCode: tabList[c].key }, true)
  }
  // 触摸开始事件
  const touchStart = function (e) {
    if (!restaList.length) return
    touchStartX = e.changedTouches[0].pageX // 获取触摸时的原点
    touchStartY = e.changedTouches[0].pageY // 获取触摸时的原点
    // 使用js计时器记录时间
    interval = setInterval(function () {
      time++
    }, 100)
  }

  // 触摸结束事件
  const touchEnd = function (e) {
    if (!restaList.length) return
    touchEndX = e.changedTouches[0].pageX // 获取触摸时的原点
    touchEndY = e.changedTouches[0].pageY // 获取触摸时的原点
    var moveX = touchEndX - touchStartX
    var moveY = touchEndY - touchStartY
    if (Math.sign(moveX) == -1) {
      moveX = moveX * -1
    }
    if (Math.sign(moveY) == -1) {
      moveY = moveY * -1
    }
    if (moveX <= moveY) {
      // 上下
      // 向上滑动
      if (touchEndY - touchStartY <= -30 && time < 10) {
        console.log("向上滑动")
        setScrollMove(2)
      }
      // 向下滑动
      if (touchEndY - touchStartY >= 30 && time < 10) {
        console.log("向下滑动")
        const query = Taro.createSelectorQuery()
        query.select(".restaurant-card").boundingClientRect()
        query.exec(function (res) {
          console.log(res[0].top)
          if (res[0].top >= criticalValue) {
            setScrollMove(1)
          }
        })
      }
    }
    clearInterval(interval) // 清除setInterval
    time = 0
  }
  // 热门餐厅上拉动画
  const moveToTop = () => {
    animation.height(topHeight).step({
      duration: duration,
      timingFunction: "ease",
    })
    setcCurrentLocation("TOP")
    setScrollMove(0)
    setAnimationData(animation.export())
  }

  // 热门餐厅下滑动画
  const moveToEnd = () => {
    animation.height(consultHeight).step({
      duration: duration,
      timingFunction: "ease",
    })
    setcCurrentLocation("END")
    setScrollMove(0)
    setAnimationData(animation.export())
  }
  // 获取餐厅类型
  const getRestaurantType = async () => {
    const res = await Http.get("/diet/public/dict/restaurantType")
    let types = res.data.map(r => {
      r.title = r.value
      return r
    })
    setTabList([...tabList, ...types])
  }
  // 获取餐厅列表
  const getRestaurantList = (query, tag) => {
    setRestaList([])
    setLoadStatus("loading")
    setVriticalValue(120)
    const params = {
      typeCode: "top",
      current: 1,
      pageSize: pageData.pageSize,
      ...query,
    }
    Http.get("/diet/restaurant/top", params).then(({ data }) => {
      const { list, current, pageSize, total } = data
      if (list.length) {
        let arr = tag ? [...list] : [...restaList, ...list]
        setRestaList(arr)
        setPageData({
          current: current,
          pageSize: pageSize,
          total: total,
        })
        setLoadStatus(total <= pageSize * current ? "noMore" : "more")
      } else {
        setLoadStatus("noMore")
      }
    })
  }
  const goToRestaurant = resa => {
    Taro.navigateTo({ url: `/pages/restaurantMenus/index?title=${resa.name}&id=${resa.id}` })
  }
  const handleInit = async () => {
    let pageHeight = await getPageHeight()
    topHeight = pageHeight - pageHeight * 0.2
    getRestaurantType()
    getRestaurantList({ typeCode: "top", current: 1 }, false)
  }

  useEffect(() => {
    handleInit()
  }, [])

  useEffect(() => {
    if (currentLocation === "END" && scrollMove === 2) {
      moveToTop()
    } else if (currentLocation === "TOP" && scrollMove === 1) {
      moveToEnd()
    }
  }, [scrollMove, currentLocation])
  useEffect(() => {
    moveToEnd()
  }, [consultHeight])

  const onScroll = e => {
    setVriticalValue(260)
  }
  const renderRestaurant = resta => {
    return (
      <View
        className="restaurant-card"
        key={resta.id}
        onClick={() => {
          goToRestaurant(resta)
        }}
      >
        <View className="card-title">
          <View className="title-name">
            <Image className="res-icon" src={resta.img ?? defaultIcon} />
            <View className="res-sum">
              <View className="res-name">{resta.name}</View>
              <View className="res-desc">
                <Image className="desc-icon" src={resta.cuisineCode === "jiangzhecai" ? jiangzhecai : chuancai} />
                {resta.cuisine}
              </View>
            </View>
          </View>
          <View className="title-like">
            <View className="like-desc">
              <Image className="desc-icon" src={recommend} />
              {resta.recommendScore}+
            </View>
            <View className="like-type">糖友推荐</View>
          </View>
        </View>
        {resta.topFoods.length ? (
          <>
            <View className="card-divider" />
            <View className="card-eated">
              <View className="eated-title">糖友吃过</View>
              <View className="eated-list">
                {resta.topFoods.map(f => (
                  <Image className="list-icon" key={f.id} src={f.img} />
                ))}
              </View>
            </View>
          </>
        ) : (
          ""
        )}
      </View>
    )
  }
  return (
    <View className="hot-restaurant" onTouchStart={touchStart} onTouchEnd={touchEnd}>
      <AtTabs current={currentTab} tabList={tabList} onClick={handleClick} scroll>
        {tabList.map((tab, index) => {
          return (
            <AtTabsPane current={currentTab} key={tab.key} index={index}>
              <ScrollView
                animation={animationData}
                lowerThreshold={100}
                onScrollToLower={() => {
                  if (restaList.length < pageData.total) {
                    getRestaurantList({ typeCode: tabList[currentTab].key, current: pageData.current + 1 }, false)
                  }
                }}
                scrollY={currentLocation === "TOP"}
                className="hot-content"
                style={{ height: consultHeight }}
                onScroll={onScroll}
              >
                {restaList.map(resta => renderRestaurant(resta))}
                <AtLoadMore status={loadStatus} />
              </ScrollView>
            </AtTabsPane>
          )
        })}
      </AtTabs>
    </View>
  )
}

index.scss

.hot-restaurant {
  box-sizing: border-box;
  background-color: #fbfbfb;
  width: 100%;
  // min-height: 530rpx;
  max-height: 100vh;
  border-radius: 40rpx 40rpx 0 0;
  position: fixed;
  padding: 30rpx 48rpx 0 48rpx;
  bottom: 0;
  left: 0;
  background: linear-gradient(180deg, #ffffff 0%, #ffffff 39%, #f2f2f2 100%);
  box-shadow: 0rpx -12rpx 24rpx 0rpx rgba(0, 0, 0, 0.02);
  z-index: 2;
}
.at-tabs__header {
  text-align: left;
  background-color: transparent;
  margin-left: -24rpx;
}
.at-tabs__item {
  font-size: 28rpx;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
}
.at-tabs__underline {
  display: none;
}
.at-tabs__item-underline {
  width: 76%;
  margin-left: 12%;
  height: 8rpx;
  background-color: #ff941a;
  bottom: 27rpx;
  opacity: 0.7;
}
.at-tabs__item--active {
  font-size: 36rpx;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: 500;
  color: #181818;
}
.hot-content {
  box-sizing: border-box;
  padding: 10rpx 0rpx 0rpx 0rpx;
  text-align: center;

  .at-button--full {
    border: none;
    font-size: 28rpx;
  }
}
.restaurant-card {
  box-sizing: border-box;
  width: 100%;
  // height: 336rpx;
  background: #ffffff;
  border-radius: 32rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0rpx 8rpx 15rpx 0rpx rgba(0, 0, 0, 0.05);
}
.card-title {
  height: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.title-name {
  flex-shrink: 1;
  height: 100%;
  flex: 1;
  display: flex;
  justify-content: flex-start;
}
.res-icon {
  background-color: #f5f5f5;
  width: 120rpx;
  height: 120rpx;
  border-radius: 20rpx;
  margin-right: 16rpx;
}
.res-sum {
  height: 120rpx;
  font-size: 34rpx;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #181818;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}

.res-name {
  width: 280rpx;
  text-align: left;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.res-desc {
  font-size: 26rpx;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 4rpx;
}
.desc-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 4rpx;
}
.title-like {
  width: 172rpx;
  height: 104rpx;
  background: #f8f8f8;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  opacity: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.like-type {
  font-size: 28rpx;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
}
.like-desc {
  font-size: 28rpx;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
  display: flex;
  justify-content: center;
  align-items: center;
}
.card-divider {
  width: 100%;
  height: 0rpx;
  opacity: 0.7;
  border-bottom: 1rpx solid #e1e1e1;
}
.card-eated {
  height: 50%;
}
.eated-title {
  font-size: 24rpx;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
  text-align: left;
  margin: 10rpx 0;
}
.eated-list {
  display: flex;
  justify-content: flex-start;
}
.list-icon {
  width: 88rpx;
  height: 88rpx;
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,039评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,426评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,417评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,868评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,892评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,692评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,416评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,326评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,782评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,957评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,102评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,790评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,442评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,996评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,113评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,332评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,044评论 2 355

推荐阅读更多精彩内容