当前位置:首页 » 程序代码 » 正文

List组件新增项,删除项的代码 arkts

@Entry
@Component
struct Page9 {
  @State itemList: string[] = ['Item1', 'Item2', 'Item3'];

  @Builder
  deleteItem(index: number) {
    Button('删除此项')
      .fontSize(15)
      .margin({ left: 10 })
      .onClick(() => {
        //删除1项方法1
        this.itemList = this.itemList.filter((_, i) => i !== index);

        //删除2项方法2 - 源码来自wb98.com
        // this.itemList.splice(index, 1);
        // this.itemList = [...this.itemList];
      })
  }

  addItem() {
    this.itemList = [...this.itemList, `Item${this.itemList.length + 1}`];
  }

  build() {
    Column({ space: 10 }) {
      Button('新增一项 +')
        .onClick(() => {
          this.addItem()
        })

      Button('全部删除 -')
        .onClick(() => {
          this.itemList=[]
        })

      List({ space: 10 }) {
        ForEach(this.itemList, (item: string, index: number) => {
          ListItem() {
            Text(item).fontSize(30).width('100%').backgroundColor(Color.White)
          }
          .swipeAction({
            end: {//右向左划
              builder: () => {
                this.deleteItem(index)
              },
            }
          })
        }, (item: string) => item)
      }
      .padding(10)
      .backgroundColor(0xDCDCDC)
      .width('100%')
      .layoutWeight(1)

    }
  }
}


打赏 支付宝打赏 微信打赏

来源:济亨网

本文链接:https://www.wb98.com/post/388.html

arkts  鸿蒙  
    << 上一篇 下一篇 >>

    湘公网安备 43011102000514号 - 湘ICP备08100508号