组件写到微信小程序的头部导航位置

53 阅读1分钟

要把组件写到微信小程序的头部导航位置,可以使用小程序的自定义导航栏功能。 

首先,在app.json文件中,设置"navigationStyle"为"custom",这样小程序的导航栏将会被自定义。

然后,在app.json文件中,设置"usingComponents",将组件的路径引入到小程序中。

接下来,在app.js文件中,使用wx.getSystemInfoSync()方法获取导航栏的高度,并将其保存到全局变量中。

最后,在需要使用组件的页面的json文件中,使用"navigationBarTitleText"设置页面的标题,并在"usingComponents"中引入组件。

具体代码如下所示:

app.json文件:

{  
  "navigationStyle": "custom",  
  "usingComponents": {  
    "custom-navigation-bar": "/components/custom-navigation-bar/custom-navigation-bar"  
  }  
}  

app.js文件:

App({  
  onLaunchfunction () {  
    // 获取导航栏的高度  
    const systemInfo = wx.getSystemInfoSync();  
    const statusBarHeight = systemInfo.statusBarHeight;  
    const headerHeight = 44;  
    const topHeight = statusBarHeight + headerHeight;  
    this.globalData.topHeight = topHeight;  
  },  
  globalData: {  
    topHeight0  
  }  
})  

页面的json文件:

{  
  "navigationBarTitleText": "页面标题",  
  "usingComponents": {  
    "custom-navigation-bar": "/components/custom-navigation-bar/custom-navigation-bar"  
  }  
}  

最后,在需要使用组件的页面的wxml文件中,引入组件,并设置组件的样式,将其放置在头部导航的位置。

<view style="height: {{topHeight}}px;"> <!-- 设置组件的高度 -->  
  <custom-navigation-bar></custom-navigation-bar> <!-- 引入组件 -->  
</view>  

需要注意的是,自定义导航栏需要使用自定义组件,所以需要在相应的文件夹中创建custom-navi