微信小程序電商實(shí)戰(zhàn)-自定義頂部導(dǎo)航欄

夢(mèng)想.jpg

感謝讀者@Followyour的好心提醒,對(duì)于安卓機(jī),下拉刷新確實(shí)無(wú)法做到導(dǎo)航欄不跟著下拉,特此做一下修正,并且自定義導(dǎo)航欄存在它的不足,比如部分安卓機(jī)型無(wú)法獲取statusBarHeight,因此給予一個(gè)默認(rèn)值20PX,但這并不能完全覆蓋所有機(jī)型,還有一點(diǎn)是使用自定義導(dǎo)航欄對(duì)于web-view的兼容性未做測(cè)試

本文章是一個(gè)系列文章,以一個(gè)完整的可用于生產(chǎn)的實(shí)際項(xiàng)目探索微信小程序開發(fā)中我們經(jīng)常會(huì)遇到的問題,希望能提供完美的解決方案,這次是本系列文章的第二篇了,以下列出該系列文章鏈接。

  1. 微信小程序及h5,基于taro,zoro最佳實(shí)踐探索
  2. 微信小程序電商實(shí)戰(zhàn)-登錄模塊設(shè)計(jì)

微信自6.6.0版本之后提供了自定義頂部導(dǎo)航欄的功能,這使得我們的全屏頁(yè)面設(shè)計(jì)成為了可能

首先演示下最終的實(shí)現(xiàn)效果


微信小程序自定義導(dǎo)航欄演示.gif

我們實(shí)現(xiàn)了一個(gè)與微信之前的導(dǎo)航欄行為基本一致,樣式可自定義的導(dǎo)航欄,接下來(lái)讓我們一步一步實(shí)現(xiàn)它,這里主要需要考慮如下幾點(diǎn)

  • 不同的手機(jī),狀態(tài)欄高度不同,需要進(jìn)行相關(guān)適配
  • 當(dāng)開啟小程序下拉刷新時(shí),如何讓頂部導(dǎo)航不會(huì)跟著下拉(僅IOS有效)
  • 自定義導(dǎo)航欄封裝成獨(dú)立組件,實(shí)現(xiàn)僅需引入到頁(yè)面,無(wú)需對(duì)頁(yè)面樣式做相關(guān)適配工作

該項(xiàng)目托管于github,有興趣的可以直接查看源碼,weapp-clover,如何運(yùn)行項(xiàng)目源碼請(qǐng)查看ztaro

要想實(shí)現(xiàn)自定義導(dǎo)航,首先我們需要配置navigationStyle為custom(src/app.js)

config = {
  window: {
    navigationStyle: 'custom'
  }
}

再實(shí)際情況中,我們往往需要對(duì)自定義導(dǎo)航進(jìn)行各種各樣的定制化,因此我們希望,封裝一個(gè)最基本的導(dǎo)航欄,用于解決適配問題,其他樣式的導(dǎo)航欄僅需對(duì)其進(jìn)行二次封裝,無(wú)需在關(guān)心適配問題,對(duì)于這個(gè)項(xiàng)目,我們封裝組件如下:

ComponentBaseNavigation 導(dǎo)航欄基本組件,用于解決適配問題
ComponentHomeNavigation 引入基本導(dǎo)航組件,定制化首頁(yè)導(dǎo)航欄組件
ComponentCommonNavigation 引入基本導(dǎo)航組件,定制化其他頁(yè)面導(dǎo)航組件

ComponentBaseNavigation實(shí)現(xiàn)

對(duì)于適配不通手機(jī)頂部的狀態(tài)欄高度,我們需要利用微信wx.getSystemInfo獲取狀態(tài)欄的高度,因此在user model中新增如下代碼(src/models/user.js)

// 省略其他無(wú)關(guān)代碼
import Taro from '@tarojs/taro'

export default {
  namespace: 'user',

  mixins: ['common'],

  state: {
    systemInfo: {},
  },

  async setup({ put }) {
    // 新增初始化獲取用戶手機(jī)系統(tǒng)相關(guān)信息,存儲(chǔ)到redux全局狀態(tài)中
    Taro.getSystemInfo().then(systemInfo =>
      put({ type: 'update', payload: { systemInfo } }),
    )
  }
}

實(shí)現(xiàn)組件邏輯(src/components/base/navigation/navigation.js)

import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import './navigation.scss'

@connect(({ user }) => ({
  // 鏈接redux中存儲(chǔ)的狀態(tài)欄高度到組件中
  statusBarHeight: user.systemInfo.statusBarHeight,
}))
class ComponentBaseNavigation extends Component {
  static defaultProps = {
    color: 'white',
    backgroundColor: '#2f3333',
  }

  render() {
    const { statusBarHeight, backgroundColor, color } = this.props

    const barStyle = {
      paddingTop: `${statusBarHeight || 20}px`,
      backgroundColor,
      color,
    }

    return (
      <View className="navigation">
        <View className="bar" style={barStyle}>
          {this.props.children}
        </View>
        <View className="placeholder" style={barStyle} />
      </View>
    )
  }
}

export default ComponentBaseNavigation

樣式如下(src/components/base/navigation.scss)

// 大寫的PX單位是為了告訴Taro,不要轉(zhuǎn)換成單位rpx
// 通過(guò)測(cè)試和觀察發(fā)現(xiàn),微信頂部的膠囊寬高如下,并且各個(gè)屏幕下一致
// 因此采用PX單位
$capsule-padding: 6PX; // 膠囊的上下padding距離
$capsule-height: 32PX; // 膠囊的高度
$capsule-width: 88PX; // 膠囊的寬度

$navigation-height: $capsule-padding * 2 + $capsule-height;
$navigation-font-size: 15PX;
$navigation-icon-font-size: 25PX;
$navigation-box-shadow: 0 2PX 2PX #222;

.navigation {
  position: relative;
  background: transparent;
  
  .bar {
    position: fixed;
    top: 0;
    left: 0;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: $navigation-height;
    z-index: 1;
    font-size: $navigation-font-size;
  }

  .placeholder {
    display: block;
    height: $navigation-height;
    background: transparent;
  }
}

要解決我們先前提到的問題當(dāng)開啟小程序下拉刷新時(shí),如何讓頂部導(dǎo)航不會(huì)跟著下拉,僅僅只需設(shè)置.bar樣式為position: fixed,這樣當(dāng)我們下拉刷新時(shí)導(dǎo)航欄就不會(huì)跟著動(dòng)了,那為什么我們還需要.placeholder標(biāo)簽?zāi)?/p>

如果你嘗試著去掉它,并且運(yùn)行查看效果時(shí),你會(huì)發(fā)現(xiàn),頁(yè)面的內(nèi)容會(huì)被頂部導(dǎo)航欄遮擋了,我們需要對(duì)每個(gè)頁(yè)面進(jìn)行額外的設(shè)置以使它如預(yù)期一樣顯示,比如給每個(gè)頁(yè)面設(shè)置頂部padding,這樣的消耗太大,因此我們專門設(shè)置placeholder標(biāo)簽占據(jù)與導(dǎo)航欄相同的高度,使頁(yè)面不被遮擋,且無(wú)需額外處理

ComponentHomeNavigation實(shí)現(xiàn)

有了這樣一個(gè)基礎(chǔ)組件,我們要實(shí)現(xiàn)首頁(yè)導(dǎo)航欄效果就變得相當(dāng)?shù)暮?jiǎn)單了,直接上代碼(src/components/home/navigation/navigation.js)

import Taro, { Component } from '@tarojs/taro'
import { View, Image, Text } from '@tarojs/components'

import { noop } from '../../../utils/tools'
import ComponentBaseNavigation from '../../base/navigation/navigation'

import './navigation.scss'

class ComponentHomeNavigation extends Component {
  static defaultProps = {
    onSearch: noop,
  }

  render() {
    const { onSearch } = this.props

    return (
      <ComponentBaseNavigation>
        <View className="navigation">
          <Image className="logo" src="@oss/logo.png" />
          <View className="search" onClick={onSearch}>
            <View className="icon iconfont icon-search" />
            <Text className="text">搜索</Text>
          </View>
        </View>
      </ComponentBaseNavigation>
    )
  }
}

export default ComponentHomeNavigation

引入導(dǎo)航組件到首頁(yè)中, 省略樣式代碼(src/pages/home/home.js)

import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { dispatcher } from '@opcjs/zoro'

import ComponentCommonLogin from '../../components/common/login/login'
import ComponentCommonSlogan from '../../components/common/slogan/slogan'
// 引入導(dǎo)航組件
import ComponentHomeNavigation from '../../components/home/navigation/navigation'
import ComponentHomeCarousel from '../../components/home/carousel/carousel'
import ComponentHomeBrand from '../../components/home/brand/brand'

import './home.scss'

class PageHome extends Component {
  config = {
    enablePullDownRefresh: true,
  }

  state = {
    // 請(qǐng)到README.md中查看此參數(shù)說(shuō)明
    __TAB_PAGE__: true, // eslint-disable-line
  }

  componentDidMount() {
    dispatcher.banner.getBannerInfo()
    dispatcher.brand.getHotBrandList()
  }

  onPullDownRefresh() {
    Promise.all([
      dispatcher.banner.getBannerInfo(),
      dispatcher.brand.getHotBrandList(),
    ])
      .then(Taro.stopPullDownRefresh)
      .catch(Taro.stopPullDownRefresh)
  }

  handleGoSearch = () => Taro.navigateTo({ url: '/pages/search/search' })

  render() {
    return (
      <View className="home">
        <ComponentCommonLogin />
        <ComponentHomeNavigation onSearch={this.handleGoSearch} />
        <ComponentHomeCarousel />
        <View class="content">
          <ComponentCommonSlogan />
          <ComponentHomeBrand />
        </View>
      </View>
    )
  }
}

export default PageHome

ComponentCommonNavigation實(shí)現(xiàn)

該組件的實(shí)現(xiàn)方式與首頁(yè)基本一致,需要提的一點(diǎn)就是返回鍵的實(shí)現(xiàn),我們?cè)撊绾谓y(tǒng)一的判斷該頁(yè)面是否需要返回鍵呢,這里需要利用微信接口wx.getCurrentPages(),實(shí)現(xiàn)代碼如下(src/components/common/navigation/navigation.js)

import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import classNames from 'classnames'

import ComponentBaseNavigation from '../../base/navigation/navigation'

import './navigation.scss'

class ComponentCommonNavigation extends Component {
  static defaultProps = {
    title: '',
  }

  state = {
    canBack: false,
  }

  componentDidMount() {
    // 獲取當(dāng)前頁(yè)面是否需要返回鍵
    const canBack = Taro.getCurrentPages().length > 1
    this.setState({ canBack })
  }

  handleGoHome = () => Taro.switchTab({ url: '/pages/home/home' })
  
  handleGoBack = () => Taro.navigateBack()

  render() {
    const { title } = this.props
    const { canBack } = this.state

    return (
      <ComponentBaseNavigation>
        <View className={classNames('navigation', { padding: !canBack })}>
          <View className="tools">
            {canBack && (
              <View
                className="iconfont icon-arrow-left back"
                onClick={this.handleGoBack}
              />
            )}
            <View
              className="iconfont icon-home home"
              onClick={this.handleGoHome}
            />
          </View>
          <View className="title">{title}</View>
        </View>
      </ComponentBaseNavigation>
    )
  }
}

export default ComponentCommonNavigation

感謝觀看,文筆不佳,不能完全表達(dá)出設(shè)計(jì)思路,代碼是最好的表達(dá),移步weapp-clover

本項(xiàng)目會(huì)持續(xù)完善,如有興趣,請(qǐng)關(guān)注一波

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容