鸿蒙实现三级联动选择框

发布时间:2023年12月22日
import Prompt from '@system.prompt';
import { FirstLevelComponent } from './FirstLevelComponent';
import { SecondLevelComponent } from './SecondLevelComponent';
import { ThirdLevelComponent } from './ThirdLevelComponent';

@CustomDialog
export default struct DataPickerDialog {
  @Provide currentFirst: JSON = null;
  @Provide currentSecondBean: JSON = null;
  @Provide currentThirdBean: JSON = null;
  controller: CustomDialogController
  title: string = '这是标题' //弹窗的提示文本
  @Provide dataSource: JSON[] = null
  defaultValue: JSON[] = null
  result: JSON[] = [];

  aboutToAppear() {
    let jsonStr: string = '{"defaultValue":[{"name":"河南省","value":"002"},{"name":"平顶山市","value":"002002"},{"name":"宝丰县","value":"002002002"}],"dataSource":[{"name":"浙江省","value":"001","children":[{"name":"杭州市","value":"001001","children":[{"name":"拱墅区","value":"001001001","children":[]},{"name":"西湖区","value":"001001002","children":[]}]},{"name":"湖州市","value":"001002","children":[{"name":"南浔区","value":"001002001","children":[]},{"name":"吴兴区","value":"001002002","children":[]}]}]},{"name":"河南省","value":"002","children":[{"name":"郑州市","value":"002001","children":[{"name":"金水区","value":"002001001","children":[]},{"name":"二七区","value":"002001002","children":[]}]},{"name":"平顶山市","value":"002002","children":[{"name":"鲁山县","value":"002002001","children":[]},{"name":"宝丰县","value":"002002002","children":[]}]}]},{"name":"河北省省","value":"003","children":[{"name":"石家庄市","value":"003001","children":[{"name":"一一区","value":"003001001","children":[]},{"name":"22区","value":"003001002","children":[]}]},{"name":"保定市","value":"003002","children":[{"name":"三三区","value":"003002001","children":[]},{"name":"四四区","value":"003002002","children":[]}]}]},{"name":"山东省","value":"004","children":[{"name":"青岛市","value":"004001","children":[{"name":"青岛市1区","value":"004001001","children":[]},{"name":"青岛市2区","value":"004001002","children":[]}]},{"name":"济南市","value":"004002","children":[{"name":"济南1区","value":"004002001","children":[]},{"name":"济南2区","value":"004002002","children":[]}]}]}]}'
    let json: JSON = JSON.parse(jsonStr);
    this.dataSource = json['dataSource']
    this.defaultValue = json['defaultValue']

    this.currentFirst = this.defaultValue[0];
    this.currentSecondBean = this.defaultValue[1];
    this.currentThirdBean = this.defaultValue[2];
  }

  build() {
    Column() {
      Text(this.title)
        .fontSize(25)
        .textAlign(TextAlign.Center)
        .margin({ top: 10, bottom: 10 });
      Row() {
        FirstLevelComponent().width('30%');
        SecondLevelComponent().width('35%');
        ThirdLevelComponent().width('35%');
      }.height('40%')

      Flex({ justifyContent: FlexAlign.SpaceAround, alignItems: ItemAlign.Center }) {
        Button('取消', { type: ButtonType.Normal })
          .onClick(() => {
            this.controller.close()
          })
          .backgroundColor(0xffffff)
          .fontColor(Color.Black)
          .layoutWeight(1)
          .height('100%')
        Divider()
          .vertical(true)
          .strokeWidth(1)
          .color('#F1F3F5')
          .opacity(1)
          .height('100%')
        Button('确认', { type: ButtonType.Normal })
          .onClick(() => {
            this.controller.close()
            this.currentFirst['children'] = ''
            this.currentSecondBean['children'] = ''
            this.currentThirdBean['children'] = ''
            this.result.push(this.currentFirst)
            this.result.push(this.currentSecondBean)
            this.result.push(this.currentThirdBean)
            console.log("wang", JSON.stringify(this.result))

          })
          .backgroundColor(0xffffff)
          .fontColor(Color.Blue)
          .layoutWeight(1)
          .height('100%')
      }.height(50)
    }
  }
}

这个是主要页面

@Component
export struct FirstLevelComponent {
  @State labelList: string[] = [];
  @State select: number = 0;
  @Consume currentFirst: JSON;
  @Consume dataSource: JSON[];

  aboutToAppear() {
    for (let i = 0; i < this.dataSource.length; i++) {
      this.labelList.push(this.dataSource[i]['name'])
      if (this.dataSource[i]['value'] == this.currentFirst['value']) {
        this.select = i;
      }
    }
    this.currentFirst = this.dataSource[this.select]
  }

  build() {
    Column() {
      Column() {
        if (this.labelList.length === 0) {
          Text('暂无数据').fontSize(20)
        } else {
          TextPicker({ range: this.labelList, selected: this.select })
            .onChange((value: string, index: number) => {
              this.select = index
              this.currentFirst = this.dataSource[index]
            })
        }
      }
      .backgroundColor(Color.White)
      .border({ color: '#e2e2e2', width: { right: 0.5 }
      })
      .width('100%')
      .layoutWeight(1)
      .justifyContent(FlexAlign.Center)
    }
    .height('100%')
  }
}

@Component
export struct SecondLevelComponent {
  @State mTip: string = '暂无数据'
  @Consume @Watch('onFirstChange') currentFirst: JSON;
  @Consume currentSecondBean: JSON;
  @State labelList: string[] = [];
  @State select: number = 0;

  build() {
    Column() {
      Column() {
        if (this.labelList.length === 0) {
          Text(this.mTip).fontSize(20)
        } else {
          TextPicker({ range: this.labelList, selected: this.select })
            .onChange((value: string, index: number) => {
              this.select = index
              this.currentSecondBean = this.currentFirst['children'][index]
            })
        }
      }
      .backgroundColor(Color.White)
      .border({
        color: '#e2e2e2',
        width: { right: 0.5 }
      })
      .width('100%')
      .layoutWeight(1)
      .justifyContent(FlexAlign.Center)
    }
    .height('100%')
  }

  onFirstChange() {
    if (!this.currentFirst) {
      this.mTip = '暂无数据';
    } else {
      this.labelList = []
      for (let i = 0; i < this.currentFirst['children'].length; i++) {
        this.labelList.push(this.currentFirst['children'][i]['name'])
        if (this.currentFirst['children'][i]['value'] == this.currentSecondBean['value']) {
          this.select = i;
        }
      }
      this.currentSecondBean = this.currentFirst['children'][this.select]
    }
  }
}


@Component
export struct ThirdLevelComponent {
  @State mTip: string = '暂无数据'
  @Consume @Watch('onFirstChange') currentFirst: JSON;
  @Consume @Watch('onSecondChange') currentSecondBean: JSON;
  @Consume currentThirdBean: JSON;
  @State labelList: string[] = [];
  @State select: number = 0;

  build() {
    Column() {
      Column() {
        if (this.labelList.length === 0) {
          Text(this.mTip).fontSize(20)
        } else {
          TextPicker({ range: this.labelList, selected: this.select })
            .onChange((value: string, index: number) => {
              this.select = index
              this.currentThirdBean = this.currentSecondBean['children'][this.select]
            })
        }
      }
      .backgroundColor(Color.White)
      .border({
        color: '#e2e2e2',
        width: { right: 0.5 }
      })
      .width('100%')
      .layoutWeight(1)
      .justifyContent(FlexAlign.Center)
    }
    .height('100%')
  }

  onFirstChange() {
  }

  onSecondChange() {
    if (!this.currentSecondBean) {
      this.mTip = '暂无数据';
    } else {
      this.labelList = []
      for (let i = 0; i < this.currentSecondBean['children'].length; i++) {
        this.labelList.push(this.currentSecondBean['children'][i]['name'])
        if (this.currentSecondBean['children'][i]['value'] == this.currentThirdBean['value']) {
          this.select = i;
        }
      }
      this.currentThirdBean = this.currentSecondBean['children'][this.select]
    }
  }
}
文章来源:https://blog.csdn.net/hasayaqimomo/article/details/135090534
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。