当前位置:   article > 正文

ArkTs中的@builder复用组件后修改数据不进行更新_arkts 组件复用

arkts 组件复用
  1. @Entry
  2. @Component
  3. struct BuilderCase{
  4. // 定义响应式数据
  5. @State formData: CardClass = {
  6. time: "2023-12-12",
  7. location: '回龙观',
  8. type: '漏油'
  9. }
  10. // 使用builder抽离组件
  11. @Builder
  12. //string是一个基础数据类型,它是按值传递的,不具备响应式更新的特点
  13. getCellContent(leftTitle: string, rightValue: string) {
  14. Row() {
  15. Row() {
  16. Text(leftTitle)
  17. Text(rightValue)
  18. }
  19. .width('100%')
  20. .justifyContent(FlexAlign.SpaceBetween)
  21. .padding({
  22. left: 15,
  23. right: 15
  24. })
  25. .borderRadius(8)
  26. .height(40)
  27. .backgroundColor(Color.White)
  28. }.padding({
  29. left: 10,
  30. right: 10
  31. })
  32. }
  33. build() {
  34. Row() {
  35. Column({space:10}) {
  36. Text(JSON.stringify(this.formData))
  37. // 复用builder抽离的组件
  38. this.getCellContent("异常类型",this.formData.type)
  39. this.getCellContent("异常时间",this.formData.time)
  40. this.getCellContent("异常地址",this.formData.location)
  41. // 点击修改数据后查看ui是否更换
  42. Button("修改地址")
  43. .onClick(()=>{
  44. this.formData.location='陕西'
  45. })
  46. }
  47. .width('100%')
  48. }
  49. .height('100%')
  50. .backgroundColor('#ccc')
  51. }
  52. }
  53. class CardClass {
  54. time: string = ""
  55. location: string = ""
  56. type: string = ""
  57. }

那是因为builder函数传入的数据是基本数据类型,不具备响应式的特点

按引用传递参数时,传递的参数可为状态变量,且状态变量的改变会引起@Builder方法内的UI刷新。ArkUI提供$$作为按引用传递参数的范式。

ABuilder( $$ : 类型 );
  1. class CellParams {
  2. leftTitle: string = ""
  3. rightValue: string = ""
  4. }
  5. @Builder
  6. // 也就是我们需要在builder中传入一个对象, 该对象使用$$(可使用其他字符)的符号来修饰,此时数据具备响应式了
  7. function getCellContent($$: CellParams) {
  8. Row() {
  9. Row() {
  10. Text($$.leftTitle)
  11. Text($$.rightValue)
  12. }
  13. .width('100%')
  14. .justifyContent(FlexAlign.SpaceBetween)
  15. .padding({
  16. left: 15,
  17. right: 15
  18. })
  19. .borderRadius(8)
  20. .height(40)
  21. .backgroundColor(Color.White)
  22. }.padding({
  23. left: 10,
  24. right: 10
  25. })
  26. }

那么此时复用的builde函数的参入也应该传入一个对象

  1. Column({space:10}) {
  2. Text(JSON.stringify(this.formData))
  3. this.getCellContent({leftTitle:"异常类型",rightValue:this.formData.type})
  4. this.getCellContent({leftTitle:"异常时间",rightValue:this.formData.time})
  5. this.getCellContent({leftTitle:"异常地址",rightValue:this.formData.location})
  6. Button("修改地址")
  7. .onClick(()=>{
  8. this.formData.location='陕西'
  9. })
  10. }

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号