ArkTS学习

146 阅读5分钟

存储数据

变量存储

变量存储数据可改变

let str:string = 'david' //string
let num:number = 66 //number
let islogin:boolean =false //boolean

常量存储

存储数据不可变

const str:string = 'david' //不可变

命名规则

  1. 只能包含数字、字母、下划线、@这些符号,不能以数字开头
  2. 不可以使用内置关键字或者保留字
  3. 严格区分大小写

数组

let 数组名: 类型[] = [数据1,数据2....];
let names:string[] = ['小明','小牛']
let nums:number[] = [1,2,3]

函数

function 函数名(形参1:类型,形参1:类型...){
      return 处理后的结果
}

//使用
let 变量名:类型 = 函数名(实参1,实参2...)

对象

//定义接口

interface 接口名 {
属性名1:类型1
...:...
...:...
}

//使用
let david:Person = {
  name:"liuxu",
  age:18,
  height:188
}

//访问属性只可以通过.的方式
console.log('',david.age)

枚举

     enum 枚举名 {
         常量1= 值,
         常量2= 值2
     }
     
     //定义
     enum ThemeColor = {
         Red= "#8f9f4d",
         Green= "#30b30e"
     }
     //使用
     const color: ThemeColor = ThemeColor.Red;

泛型

广泛的类型=>类型可以作为参数进行传递=>类型是可变的

泛型函数

function fn<T>(arr: T[]): T {
  return arr[arr.length -1]
}

console.log('', fn<number>([1, 9]))

泛型接口

// 泛型接口
interface IFn<T> {
  id: (value: T) => T
}

let obj: IFn<string> = {
  id(value: string) {
    return value
  }
}

泛型类

class Person<T> {
  id: T

  constructor(id: T) {
    this.id = id
  }

  getId(): T {
    return this.id
  }
}

状态和事件

事件点击

@Entry
@Component
struct Index {
  @State message: string = '点我';

  build() {
    Column() {
      Button(this.message).onClick(() => {
        console.log("点击了");
      })
    }
    .width('100%').height('100%')
    .backgroundColor('#f6f6f6')
  }
}

计数器案例

@Entry
@Component
struct Index {
  @State message: string = '点我';
  @State num: number = 0;

  build() {
    Column() {
      Button(this.message).onClick(() => {
        console.log("点击了");
      })

      Row({ space: 10 }) {
        Button('-').onClick(() => {
          this.num--;
        })
        Text(this.num.toString())
        Button('+').onClick(() => {
          this.num++;
        })
      }
    }
    .width('100%').height('100%')
    .backgroundColor('#f6f6f6')
  }
}

一元运算符

前置和后置

  • 前置表示先操作(自增/自减)在赋值
  • 后置表示先赋值在操作(自增/自减)

通用抽取

Extend扩展组件

  • 扩展组件的样式,事件,实现可复用
  • 可传参

@Extend语法

Extend(组件名)
function 自定义拓展名(可传参数...){
}

@Styles

  • 不支持传参,
  • 主要进行通用样式和事件的抽取
  • 可以全局定义也可以在组件内定义
@Styles commonStyle(){
}

@Builder

  • 结构样式事件都可封装,即简易版组件
  • 可定义为全局也可定义在组件
  • 可传参
@Extend(Text)
function textFn(bgColor: Color, txt: string) {
  .width('100%')
  .height(50)
  .backgroundColor(bgColor)
  .textAlign(TextAlign.Center)
  .onClick(() => {
    AlertDialog.show({
      message: `点击了${txt}`
    })
  })
}

@Styles
function allStyle() {
  .backgroundColor(Color.Red)
}

// 全局
@Builder
function menuItem(imgUrl: ResourceStr, txt: string) {
  Column({ space: 10 }) {
    Image(imgUrl)
      .width(50)
    Text(txt)
  }
}

@Entry
@Component
struct Index {
  // 局部
  @Styles
  commonStyle() {
    .width(300)
    .height(30)
    .onClick(() => {
      AlertDialog.show({
        message: 'hehe'
      })
    })
  }

  // 局部
  @Builder
  menuItem2(imgUrl: ResourceStr, txt: string) {
    Column({ space: 10 }) {
      Image(imgUrl)
        .width(50)
      Text(txt)
    }
  }

  build() {

    Column({ space: 10 }) {
      // 使用Extend扩展,通用组件的抽取
      Text('组件一')
        .textFn(Color.Red, '组件一')
      Text('组件二')
        .textFn(Color.Yellow, '组件二')
      Text('组件三')
        .textFn(Color.Blue, '组件三')

      // 通用样式的抽取
      Text('文本')
        .commonStyle()
        .allStyle()
      Button('按钮')
        .commonStyle()

      // 简易版组件的抽取
      Row({ space: 30 }) {
        // 全局定义组件使用
        menuItem($r('app.media.ic_reuse_01'), '拍卖')
        menuItem($r('app.media.ic_reuse_02'), '菜鸟')
        // 局部定义组件使用
        this.menuItem2($r('app.media.ic_reuse_03'), '粑粑农场')
        this.menuItem2($r('app.media.ic_reuse_04'), '阿里药房')
      }
    }
    .width('100%')
    .padding(10)
  }
}

scroll属性

@Entry
@Component
struct Index {
  build() {

    Column({ space: 10 }) {
      Scroll() {
        Column({ space: 5 }) {
          ForEach(Array.from({ length: 50 }), (item: string, index: number) => {
            Text(`滚动${index + 1}`)
              .width('100%')
              .height(80)
              .backgroundColor(Color.Orange)
              .textAlign(TextAlign.Center)
          })
        }
        .width('100%')
        .padding(10)
      }
      .width('100%')
      .height('100%')
      .scrollable(ScrollDirection.Vertical) //设置滚动方向
      .scrollBar(BarState.Auto) //设置滚动条显示状态,是否显示或者是滑动时才显示(Auto)
      .scrollBarWidth(10) //设置滚动条宽度
      .scrollBarColor(Color.Red) //设置滚动条颜色
      .edgeEffect(EdgeEffect.Spring) //设置滚动到某个位置的效果(弹簧效果,阴影效果)
    }
    .width('100%')
    .height('100%')
  }
}

tabbar

@Entry
@Component
struct Index {
  titles: string[] = ['首页', '关注', '热门', '军事', '体育', '八卦', '数码', '财经', '美食', '旅行'];

  build() {
    Tabs({ barPosition: BarPosition.End }) { //控制显示的位置是开头位置还是结尾位置
      ForEach(this.titles, (item: string, index: number) => {
        TabContent() {
          Column() {
            Text(`${item}内容`)
          }
        }.tabBar(item)
      })
    }
    .vertical(false) //设置是否侧边显示tab栏属性,默认为false
    .scrollable(true) //设置是否开启收拾滑动,默认开启
    .animationDuration(0) //设置没有点击切换的滑动动画
    .barMode(BarMode.Scrollable) //如果tab栏过多可以设置为滚动
  }
}

组件

通用组件抽取、参数传递

子组件

@Component
export struct MyCom {
//参数和方法都可以根据传入的进行覆盖,注意方法必须写成等号加箭头函数的形式才可以覆盖
  title: string = '默认标题'
  rightTitle: string = '查看更多 >'
  showMessage = () => {
    AlertDialog.show({
      message: '展示'
    })
  }

  build() {
    Column() {
      Row() {
        Text(this.title)
        Text(this.rightTitle)
      }
      .width('100%')
      .padding(10)
      .justifyContent(FlexAlign.SpaceBetween)

      Column() {
        Button('按钮').onClick(() => {
          this.showMessage();
        })
      }.width('100%')
    }
    .width('100%')
    .height(100)
    .backgroundColor(Color.White)
    .borderRadius(10)

  }
}

父组件

import { MyCom } from '../components/MyCom'

@Entry
@Component
struct Index {
  build() {
    Column({ space: 10 }) {
      MyCom({
        title: '我的订单', showMessage() {
          AlertDialog.show({
            message: '呵呵呵呵呵'
          })
        }
      })
      MyCom({ title: '小米优品众筹', rightTitle: '查看更多众筹 >' })
    }
    .width('100%')
    .height('100%')
    .padding(10)
    .backgroundColor('#999')
  }
}

类似插槽功能

传入一个插槽(尾随闭包传入替换内容)

子组件

@Component
export struct MyCom {
  title: string = '默认标题'
  rightTitle: string = '查看更多 >'
  //这里定义插槽的内容,可通过传递进行覆盖
  @BuilderParam ContentBuilder: () => void = this.defaultBuilder
  showMessage = () => {
    AlertDialog.show({
      message: '展示'
    })
  }

  // 默认插槽显示的内容
  @Builder
  defaultBuilder() {
    Column() {
      Text('这是默认的插槽内容')
    }
    .width('100%')
    .height(20)
    .backgroundColor(Color.Pink)
  }

  build() {
    Column() {
      Row() {
        Text(this.title)
        Text(this.rightTitle)
      }
      .width('100%')
      .padding(10)
      .justifyContent(FlexAlign.SpaceBetween)

      Column() {
        Button('按钮').onClick(() => {
          this.showMessage();
        })
        this.ContentBuilder()
      }
      .width('100%')
    }
    .width('100%')
    .height(200)
    .backgroundColor(Color.White)
    .borderRadius(10)

  }
}

父组件

import { MyCom } from '../components/MyCom'

@Entry
@Component
struct Index {
  build() {
    Column({ space: 10 }) {
      MyCom({
        title: '我的订单', showMessage() {
          AlertDialog.show({
            message: '呵呵呵呵呵'
          })
        }
      }) {
      //这里使用尾随闭包
        Column() {
          Text('这是我传递过去替换填入插槽的内容')
          Text('这是我传递过去替换填入插槽的内容')
          Text('这是我传递过去替换填入插槽的内容')
        }
      }

      MyCom({ title: '小米优品众筹', rightTitle: '查看更多众筹 >' })
    }
    .width('100%')
    .height('100%')
    .padding(10)
    .backgroundColor('#999')
  }
}

传入多个

不能使用尾随闭包,只可以使用参数传递的方式

子组件

@Component
export struct MyComBuilderParam {
  // 这里注意不能写成函数调用
  @BuilderParam titleBuilder: () => void = this.tBuilder
  @BuilderParam contentBuilder: () => void = this.cBuilder

  @Builder
  tBuilder() {
    Text('这是动态默认标题')

  }

  @Builder
  cBuilder() {
    Text('这是动态默认内容')
  }

  build() {
    Column() {
      Row() {
        this.titleBuilder()
      }
      .width('100%')
      .height(40)
      .padding(10)
      .border({ width: { bottom: 1 } })

      this.contentBuilder()
    }
    .width('100%')
    .height(200)
    .backgroundColor(Color.White)
    .borderRadius(10)
  }
}

父组件

import { MyComBuilderParam } from '../components/MyComBuilerParam'

@Entry
@Component
struct Index {
  @Builder
  titleBuilder() {
    Text('传入的第一个标题')
      .fontSize(20)
      .fontColor(Color.Red)
  }

  @Builder
  contentBuilder() {
    Text('传入的第一个内容')
      .fontSize(20)
      .fontColor(Color.Blue)
  }

  build() {
    Column({ space: 15 }) {
      MyComBuilderParam({
        titleBuilder: this.titleBuilder,
        contentBuilder: this.contentBuilder
      })
      MyComBuilderParam()
    }
    .width('100%').height('100%')
    .padding(10)
    .backgroundColor('#999')
  }
}

image.png