UI组件怎样条件执行选项函数?

我在封装web组件,web组件有很多选项函数,比如allowWindowOpenMethod,希望做到的效果是,有个自定义配置项 allowWindowOpenMethod?: boolean,如果配了就用自定义值,没配就用默认值,一个选项,可以在if-else分支中重复下web组件完整配置代码,一个分支有allowWindowOpenMethod函数,一个分支没有,web组件类似的选项有很多,怎样写比较好,可以在声明式UI中,加普通代码控制逻辑的写法。

HarmonyOS
2024-11-06 11:47:24
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu

可参考以下demo:

import web_webview from '@ohos.web.webview'; 
 
class MyButtonModifier implements AttributeModifier<ButtonAttribute> { 
  ChangeColor: boolean = false 
  applyNormalAttribute(instance: ButtonAttribute): void { 
    if (this.ChangeColor) { 
      instance.backgroundColor(Color.Red) 
    } 
  } 
} 
class MyWebModifier implements AttributeModifier<WebAttribute> { 
  ChangeWidth: boolean = false 
  applyNormalAttribute(instance: WebAttribute): void { 
    if (this.ChangeWidth) { 
      instance.width(100) 
      instance.height(200) 
    } 
  } 
} 
 
@Entry 
@Component 
struct attributeDemo { 
  @State modifier: MyButtonModifier = new MyButtonModifier() 
  @State webfier: MyWebModifier = new MyWebModifier() 
  webviewController: web_webview.WebviewController = new web_webview.WebviewController(); 
 
  onPageShow(): void { 
    //模拟接口返回或者点击事件改变状态 
    setTimeout(()=>{ 
      this.modifier.ChangeColor = !this.modifier.ChangeColor 
    },1000) 
    setTimeout(()=>{ 
      this.webfier.ChangeWidth = !this.webfier.ChangeWidth 
    },2000) 
  } 
 
 
  build() { 
    Row() { 
      Column() { 
        // web组件加载本地index.html页面 
        Web({ src: $rawfile('index.html'), controller: this.webviewController}) 
          .javaScriptAccess(true) 
          .multiWindowAccess(true) 
          .domStorageAccess(true) 
          .allowWindowOpenMethod(true) 
          .backgroundColor(Color.Green) 
          .attributeModifier(this.webfier) 
 
        Button("Button") 
          .attributeModifier(this.modifier) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
分享
微博
QQ
微信
回复
2024-11-06 15:15:16
相关问题
IF条件变化后UI不刷新
1463浏览 • 1回复 待解决
HarmonyOS 每秒执行一次的函数
1096浏览 • 2回复 待解决
如何在自定义函数中创建一个UI组件
2615浏览 • 1回复 待解决
HarmonyOS 选项组件
1015浏览 • 1回复 待解决
组件复用生效的条件有哪些?
923浏览 • 1回复 待解决
如何在ArkTS代码中执行HTML内的JS函数
3359浏览 • 1回复 待解决
元服务审核的UI检查规范是怎样的?
308浏览 • 0回复 待解决
弹窗组件调用父组件函数传递
1964浏览 • 1回复 待解决
使用自定义函数创建一个UI
986浏览 • 1回复 待解决
鸿蒙中把builder函数传参与UI渲染问题
276浏览 • 0回复 待解决