SideBarContainer侧边栏容器的基本介绍

556 阅读1分钟

在日常的开发中,有时候的界面会出现侧边栏的页面内容区域,那么就要用上SideBarContainer容器组件了,类似以下的这种页面。

image.png

1. 基本用法

语法:

 SideBarContainer(SideBarContainerType.Overlay) {
      Column() {
        // 子组件 1:侧边栏
      }
      Column() {
        // 子组件 2:内容区域
      }
    }
    .showSideBar(false) // 默认隐藏

说明:

  • 子组件类型:系统组件和自定义组件
  • 子组件个数:必须且仅包含2个子组件,第一个位置的组件作为侧边栏的内容,第二个位置的组件是内容
  • 子组件个数异常时:3个或以上子组件,显示第一个和第二个。1个子组件显示侧边栏,内容区为空白。

1.2 常用属性

image.png 具体的写法如下:

.showSideBar($$this.status) // true,false 默认隐藏

.showControlButton(true) // true:显示控制按钮(默认) false:不显示控制按钮

.sideBarWidth(350) // 设置侧边栏的宽度,默认值:240vp,超出minSideBarWidth和maxSideBarWidth设定的范围后该值无效

.sideBarPosition(SideBarPosition.End) //设置侧边栏显示位置。 默认值:SideBarPosition.Start

.minSideBarWidth(100) // 设置侧边栏最小宽度 默认值:240vp

.maxSideBarWidth(300) // 设置侧边栏最大宽度 默认值:280vp

更多的属性可以查阅文档:

SideBarContainer-容器组件-ArkTS组件-ArkUI(方舟UI框架)-应用框架 - 华为HarmonyOS开发者 (huawei.com)

1.2.1 事件

image.png

案例

学完以上的这些属性过后,就可以完成以下这个简单的页面了 image.png 需求:

  1. 关闭控制按钮
  2. 通过自定义的按钮控制显示隐藏
  3. 侧边栏位置在右侧
  4. 拖动关闭之后,可以再次开启
@Entry
@Component
struct SiderBar01 {
  @State isShow: boolean = false

  build() {
    // 容器组件
    // SideBarContainerType.Overlay 侧边栏 会盖住
    // SideBarContainerType.Embed 侧边栏 挤压内容
    SideBarContainer(SideBarContainerType.Overlay) {
      // 藏起来的侧边栏
      Column() {
        Button('关闭')
          .onClick(()=>{
            this.isShow = false
          })
        Text('我是侧边栏')
          .fontSize(25)
          .textAlign(TextAlign.Center)
      }.justifyContent(FlexAlign.Center)
      .backgroundColor('#ffa502')
      .borderRadius(15)

      // 内容
      Column() {
        // Image($r('app.media.ic_douban_main'))
        Button('点我显示')
          .onClick(() => {
            this.isShow = true
          })
      }.backgroundColor('#7f6066')
      .borderRadius({topRight:15,bottomRight:15})
    }
    .showControlButton(false) // 控制按钮显示 true / false

    .showSideBar($$this.isShow)  // $$this.isShow  是否显示 true/ false
    .sideBarPosition(SideBarPosition.End) // 设置位置  End 末尾 /Start 开头
    //.sideBarWidth('100%') // 侧边栏 宽度
    .onChange((show: boolean) => {
      // 侧边切换显示状态时触发,true 显示,false 隐藏
      console.log('show:', show)
      this.isShow = show
    })
  }
}

注意点:

  • 在侧边栏区域和主页面区域不需要单独设置高和宽,设置了也不会产生效果,如需单独设置侧边栏的宽度,使用sideBarWidth,如果你设置整个SideBarContainer的宽高,这侧边栏区域和主区域的宽高会一起变化。