DEV Community

Cover image for Search Box Component: Search Component Introduction
liu yang
liu yang

Posted on

Search Box Component: Search Component Introduction

Search Box Component Introduction

Code Implementation

Search Component Usage

build() {
  Column() {
    Row() {
      Text('Position')
        .fontSize(14)
        .fontColor(Color.Black)
        .textAlign(TextAlign.Start)
        .margin({ left: 5 });

      Search({ value: this.changeValue, placeholder: 'Enter search information', controller: this.controller })
        .searchButton(CommonConstant.SEARCH_TEXT)
        .layoutWeight(1)
        .margin({ left: 8, right: 8 })
        .backgroundColor($r('app.color.sections_back_bg'))
        .onSubmit((value: string) => {
          console.log("Value --> " + value);
          this.search(value);
        })
        .onChange((onChangeValue) => {
          console.log("onChange --> " + onChangeValue);
        });
    }
    .width('100%')
    .height(50)
    .backgroundColor(Color.White)
    .justifyContent(FlexAlign.Start);

    this.getListView();
  }
  .width('100%')
  .height('100%');
}
Enter fullscreen mode Exit fullscreen mode

In the Search component, add a controller to listen to the onSubmit and onChange methods.

List Implementation

@Builder
private getListView() {
  List({ space: commonConst.LIST_ITEM_SPACE, scroller: this.scroller }) {
    ForEach(this.dataList, (item: PositionData) => {
      ListItem() {
        Column() {
          Row() {
            Text(item?.name)
              .fontSize(20)
              .fontWeight(FontWeight.Bold)
              .fontColor(Color.Black);

            Text(item?.salary)
              .fontSize(16)
              .fontWeight(FontWeight.Bold)
              .fontColor($r('app.color.boss_blue'));
          }
          .width('100%')
          .justifyContent(FlexAlign.SpaceBetween);

          Text(item?.cname)
            .fontSize(14)
            .fontWeight(700)
            .fontColor('#333')
            .width('100%');

          Row({ space: 5 }) {
            Text('Experience不限')
              .padding(5)
              .borderRadius(2)
              .fontSize(10)
              .fontColor('#333')
              .backgroundColor('#eeeeee');

            Text('Bachelor')
              .padding(5)
              .borderRadius(2)
              .fontSize(10)
              .fontColor('#333')
              .backgroundColor('#eeeeee');

            Text('Computer Science')
              .padding(5)
              .borderRadius(2)
              .fontSize(10)
              .fontColor('#333')
              .backgroundColor('#eeeeee');
          }
          .width('100%');

          Row({ space: 10 }) {
            Image($r('app.media.app_icon'))
              .height(20)
              .width(20)
              .borderRadius(10)
              .objectFit(ImageFit.Contain);

            Text(item?.username)
              .fontSize(14)
              .width('100%')
              .fontColor($r('app.color.boss_blue'));
          }
        }
        .padding(10)
        .width('100%')
        .backgroundColor(Color.White)
        .borderRadius(10);
      };
    });
  }
  .width(commonConst.GOODS_LIST_WIDTH)
  .backgroundColor('#eeeeee')
  .edgeEffect(EdgeEffect.None);
}
Enter fullscreen mode Exit fullscreen mode

Search Request to Server

Call the search method in the onSubmit event to request data from the server and display the returned results.

async search(name: string) {
  let getName: string = 'name=';
  let searchUrl = CommonConstant.POSITIONLIKE + getName + name;
  httpRequestGet(searchUrl).then((data) => {
    Logger.error("Search request result -->" + data.toString());
    let positionModel: PositionModel = JSON.parse(data.toString());
    let msg: string = positionModel.msg;
    if (positionModel.code === 200) {
      this.searchList = positionModel.data;
      this.dataList.length = 0;
      this.dataList = [];
      this.dataList.push(...this.searchList);
    } else {
      prompt.showToast({
        message: msg
      });
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Initial Server Request

async getPosition() {
  let networkUrl = CommonConstant.POSITIONALL;
  httpRequestGet(networkUrl).then((data) => {
    Logger.error("Position request result -->" + data.toString());
    let positionModel: PositionModel = JSON.parse(data.toString());
    this.JokeList = positionModel.data;
    this.dataList.push(...this.JokeList);
  });
}
Enter fullscreen mode Exit fullscreen mode

Data Model for Server Data

export class PositionModel {
  msg: string = "";
  code: number = 0;
  data: Array<PositionData> = [];
}

@Observed
export class PositionData {
  id: string = "";
  name: string = "";
  cname: string = "";
  size: string = "";
  salary: string = "";
  username: string = "";
  title: string = "";
}
Enter fullscreen mode Exit fullscreen mode

Network Request Utility Class

import http from '@ohos.net.http';
import Logger from './Logger';
import Constants, { ContentType } from '../common/Constants';

export function httpRequestGet(url: string, params?: string): Promise<string> {
  return httpRequest(url, http.RequestMethod.GET, params);
}

export function httpRequestPost(url: string, params?: string): Promise<string> {
  return httpRequest(url, http.RequestMethod.POST, params);
}

function httpRequest(url: string, method: http.RequestMethod, params?: string): Promise<string> {
  let httpRequestObj = http.createHttp();
  let responseResult = httpRequestObj.request(url, {
    method: method,
    readTimeout: Constants.HTTP_READ_TIMEOUT,
    header: {
      'Content-Type': ContentType.JSON
    },
    connectTimeout: Constants.HTTP_READ_TIMEOUT,
    extraData: params
  });

  let getJson: string = '';
  return responseResult.then((value: http.HttpResponse) => {
    Logger.error("Request status -->" + value.responseCode);
    if (value.responseCode === 200) {
      Logger.error("Request succeeded");
      let result = `${value.result}`;
      Logger.error("Request return data", JSON.parse(result));
      getJson = result;
    } else {
      getJson = '';
    }
    return getJson;
  }).catch(() => {
    httpRequestObj.destroy();
    return '';
  });
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.