Taro 滚动切换tab页

import React, { Component } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import { createSelectorQuery } from '@tarojs/taro'
import './index.scss'

const tabList = [{name: '头', value: 'header'},{name: '内容',value: 'content'},{name: '底部', value: 'footer'}]
export default class Index extends Component {
  state ={
    activeStatus: 'header',
    heightArr: [],
    activeIndex:0
  }
  handleTab(value, index) {
    this.setState({
      activeStatus: value,
      activeIndex: index
    })
  }
  handleScroll({detail}) {
    let heightArr = []
    let number = 0
    // 获取节点距离容器顶部的高度
    tabList.map(item => {
      createSelectorQuery().select(`#${item.value}`).boundingClientRect(res => {
        number = res.height + number
        heightArr.push(number)
        this.setState({
          heightArr: heightArr
          })
      }).exec()
    })

    // 根据滚动定位节点
    const scrollTop = Math.ceil(detail.scrollTop)
    const { heightArr:scrollArr } = this.state
    this.state.heightArr.map((item, index) => {
      if(scrollTop >= 0 && scrollTop < scrollArr[0]) {
        // 第一个
        this.setState({activeIndex: 0})
      }
      if(scrollTop >= scrollArr[index - 1] && scrollTop <= scrollArr[index]) {
        // 第N个
        this.setState({activeIndex: index})
      }
    })
    
  }
  render () {
    const { activeStatus,activeIndex } = this.state
    return (
      <View className='index'>
        <View className='tabList'>
          {tabList.map((item, index) => (
            <View onClick={this.handleTab.bind(this, item.value, index)} key={item.value} className={`tab-item  ${index===activeIndex && 'active'}`}>{item.name}</View>
          ))}
        </View>
        <ScrollView style={{height: '400px'}} scrollY scrollWithAnimation scrollIntoView={activeStatus} onScroll={this.handleScroll.bind(this)}>
          <View id='header'>
            <View style={{height: '600px'}}>头</View>
          </View>
          <View id='content'>
            <View style={{height: '150px'}}>内容</View>
          </View>
          <View id='footer'>
            <View style={{height: '3000px'}}>底部</View>
          </View>
        </ScrollView>
      </View>
    )
  }
}

 

posted @ 2020-11-15 18:57  巫瞅瞅  阅读(1566)  评论(0编辑  收藏  举报