Taro 3.x 小程序導航欄高度等精確數據的hooks


hooks代碼如下,useNavInfo.tsx

import React, {useState, useEffect} from 'react'
import Taro from '@tarojs/taro'

interface INavInfo {
  statusBarHeight: number
  titleBarHeight: number
  titelBarWidth: number
  appHeaderHeight: number
  marginSides: number
  capsuleWidth: number
  capsuleHeight:number
  capsuleLeft: number
  contentHeight: number
  screenHeight: number
  windowHeight: number
}

function useNavInfo(): INavInfo {
  const [navInfo, setNavInfo] = useState({
    statusBarHeight: 0,
    titleBarHeight: 0,
    titelBarWidth: 0,
    appHeaderHeight: 0,
    marginSides: 0,
    capsuleWidth: 0,
    capsuleHeight: 0,
    capsuleLeft: 0,
    contentHeight: 0,
    screenHeight: 0,
    windowHeight: 0,
  })

  useEffect(() => {
    console.log('sssss', Taro.getSystemInfoSync())
    const { statusBarHeight, screenWidth, screenHeight, windowHeight } = Taro.getSystemInfoSync()
    // 獲取膠囊信息
    const { width, height, left, top, right } = Taro.getMenuButtonBoundingClientRect()
    // 計算標題欄高度
    const titleBarHeight = height + (top - statusBarHeight) * 2
    // 計算導航欄高度
    const appHeaderHeight = statusBarHeight + titleBarHeight
    //邊距,兩邊的
    const marginSides = screenWidth - right
    //標題寬度
    const titelBarWidth = screenWidth - width - marginSides * 3
    //去掉導航欄,屏幕剩余的高度
    const contentHeight = screenHeight - appHeaderHeight

    setNavInfo({
      statusBarHeight: statusBarHeight, //狀態欄高度
      titleBarHeight: titleBarHeight,  //標題欄高度
      titelBarWidth: titelBarWidth,  //標題欄寬度
      appHeaderHeight: appHeaderHeight, //整個導航欄高度
      marginSides: marginSides, //側邊距
      capsuleWidth: width, //膠囊寬度
      capsuleHeight: height, //膠囊高度
      capsuleLeft: left,
      contentHeight: contentHeight,
      screenHeight: screenHeight,
      windowHeight: windowHeight,
    })
  }, [])
  
  return navInfo
}


export default useNavInfo

使用:

import useNavInfo from '../hooks/useNavInfo.tsx'

function somePage(){
    const {appHeaderHeight} = useNavInfo()
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM