HarmonyOS 多端部署时,BreakpointSystem, BreakPointType找不到呢?

阅读 705
1 个回答

BreakPointType 这个是需要自行开发的一个类。这边提供了一个已经开发好的示例。可以参考响应式布局中的媒体查询对通过媒体查询监听断点的功能做简单的封装,方便后续使用参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/responsive-layout-V5

参考demo:

// common/breakpointsystem.ets
import mediaQuery from '@ohos.mediaquery'
declare interface BreakPointTypeOption<T> { xs?: T sm?: T md?: T lg?: T xl?: T xxl?: T }
export class BreakPointType<T> { options: BreakPointTypeOption<T> constructor(option: BreakPointTypeOption<T>) { this.options = option }
  getValue(currentBreakPoint: string) {
    if (currentBreakPoint === 'xs') {
      return this.options.xs
    } else if (currentBreakPoint === 'sm') {
      return this.options.sm
    } else if (currentBreakPoint === 'md') {
      return this.options.md
    } else if (currentBreakPoint === 'lg') {
      return this.options.lg
    } else if (currentBreakPoint === 'xl') {
      return this.options.xl
    } else if (currentBreakPoint === 'xxl') {
      return this.options.xxl
    } else { return undefined
    } } }
interface Breakpoint { name: string size: number mediaQueryListener?: mediaQuery.MediaQueryListener }
export class BreakpointSystem {
  private currentBreakpoint: string = 'md' private breakpoints: Breakpoint[] = [
    { name: 'xs', size: 0 },
    { name: 'sm', size: 320 },
    { name: 'md', size: 600 },
    { name: 'lg', size: 840 }
  ]
  private updateCurrentBreakpoint(breakpoint: string) {
    if (this.currentBreakpoint !== breakpoint) {
      this.currentBreakpoint = breakpoint AppStorage.Set<string>('currentBreakpoint', this.currentBreakpoint)
      console.log('on current breakpoint: ' + this.currentBreakpoint)
    }
  }
  public register() { this.breakpoints.forEach((breakpoint: Breakpoint, index) => {
    let condition:string
    if (index === this.breakpoints.length - 1) {
      condition = '(' + breakpoint.size + 'vp<=width' + ')'
    } else {
      condition = '(' + breakpoint.size + 'vp<=width<' + this.breakpoints[index + 1].size + 'vp)'
    }
    console.log(condition)
    breakpoint.mediaQueryListener = mediaQuery.matchMediaSync(condition)
    breakpoint.mediaQueryListener.on('change', (mediaQueryResult) => {
      if (mediaQueryResult.matches) {
        this.updateCurrentBreakpoint(breakpoint.name)
      }
    })
  }) }
  public unregister() {
    this.breakpoints.forEach((breakpoint: Breakpoint) => {
      if(breakpoint.mediaQueryListener){
        breakpoint.mediaQueryListener.off('change') } }) } } 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进