HarmonyOS ArkTS实现JSON数组动态渲染 原创

虹喵小仙女
发布于 2023-7-19 19:31
浏览
0收藏

原文链接:链接

HarmonyOS实现JSON数组动态渲染

创建一个数据对象类

此对象主要映射JSON数组数据,比如服务器传的数据是这样的

[
    {
        "id": 1,
        "name": "虹喵小仙女",
        "age": 19,
        "color": "#f0f0f0"
    }
]

创建的对象就是

@Observed
class PeopleInfo {
  public  id: number = ""
  public  name: string = ""
  public  age: number = ""
  public  color: string = ""

  constructor(data) {
    // 单个数据预处理
    let age = data["age"];
    if(age>18){
        this.id = data["id"]
        this.name = data["name"]
        this.color = data["color"]
    }else{
        // ...
    }
  }
}

创建组件

@Component
struct PeopleCard{
  @ObjectLink peopleInfo: PeopleInfo;

  build() {
    Row() {
      Text("名称:"+this.peopleInfo.name).width("30%")
      Text(this.peopleInfo.age).width("50%")
      Text(this.peopleInfo.color).width("20%")
    }
    .width("100%")
    .height("60vp")
    .backgroundColor("#f0f0f0")
    .borderRadius("20vp")
    .padding("15vp")
  }
}

在页面中显示

@Entry
@Component
struct Index {
  
  @State peopleInfoArray: PeopleCard[] = []
    
  aboutToAppear(){
      let people = {
        "id": 1,
        "name": "虹喵小仙女",
        "age": 19,
        "color": "#f0f0f0"
    	};
      this.PeopleCard.push(people)
  }

  build() {
    Column(){
      Scroll(this.scrollerForScroll) {
        Column() {
          Row(){
            Button("修改第一个名字"){}.onClick(()=>{
				this.peopleInfoArray[0].name = "666";
            })
          }
          .width("100%")
          .height("30vp")
          .padding({left: "20vp"})

          List({ space: 10}) {
            ForEach(this.peopleInfoArray, (item,index) => {
              ListItem() {
                PeopleCard({tagInfo: this.peopleInfoArray[index]})
              }
              .width("90%")
              .margin({left:"5%"})
              .padding({left:"10vp",right:"10vp",top:"20vp",bottom:"20vp"})
            })
          }
          .width("100%")
          .height("100%")
          .edgeEffect(EdgeEffect.None)
        }
      }.width('100%').height('100%')
    }.width('100%').height('100%')
  }
}

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
已于2023-7-19 19:33:06修改
2
收藏
回复
举报
1条回复
按时间正序
/
按时间倒序
红叶亦知秋
红叶亦知秋

前排赞一波

回复
2023-7-20 10:08:25
回复
    相关推荐