HarmonyOS中使用自定义的控制按钮模仿侧边栏的实现

34 阅读1分钟

1、效果预览图

PixPin_2025-09-03_15-55-56.gif

2、代码实现

@Entry
@Component
struct Index {
  @State showControlButton: boolean = true // 显示控制按钮开关
  @State showSideBar: boolean = false // 显示侧边栏开关

  build() {
    SideBarContainer(SideBarContainerType.Overlay) {
      // 侧边容器
      Column() {
        Button('关闭')
          .position({ x: 10, y: 10 })
          .onClick(() => {
            this.showControlButton = true
            // this.showSideBar = false
            // 动画-关闭侧边栏
            animateTo({
              duration: 500,
              curve: Curve.Linear
            }, () => {
              this.showSideBar = false
            })
          })
      }
      .backgroundColor(Color.Orange)
      .borderRadius(10)

      // .translate({})


      // 内容区
      Column() {
        if (this.showControlButton) {
          Button('开启')
            .position({ x: 10, y: 10 })
            .onClick(() => {
              this.showControlButton = false
              // this.showSideBar = true
              // 动画-开启侧边栏
              animateTo({
                duration: 500,
                curve: Curve.Linear
              }, () => {
                this.showSideBar = true
              })
            })
        }

      }
      .backgroundColor('#7f6066')

    }
    .showControlButton(false)
    .showSideBar(this.showSideBar)
    .sideBarPosition(SideBarPosition.End)
    .sideBarWidth(300)

    // .animation({
    //   duration: 500,
    //   curve: Curve.Linear
    // })

  }
}