鸿蒙开发ArkTs语法(1)

930 阅读7分钟

鸿蒙开发ArkTs

核心理念

  • ArkTs和Ts及JS的关系
    1. JS:JavaScript,常用于网页开发,页面的效果

    2. TS:TypeScript,微软开发的,比 JS 多了类型系统

    3. ArkTS:JS、TS能用的,他 基本 都能用,写 UI

    4. 注意:看文档的时候,可能需要去 JS 的文档,TS 的文档找一部分的内容。

    • 声明式UI开发范式

image.png

  • type

作用:定义一个联合类型的别名,后续可以直接通过别名来使用这个联合类型

语法: type 类型别名 = 类型

使用:

type asd = number|string 
let a1:asd = 123
let a2:asd ='你好' 

补充:typeof运算符

可以通过 typeof 运算符来获取类型,他返回的是一个字符串

typeof 表达式 -> 返回一个类型字符串

// 后面跟上需要获取类型的 数据或变量 即可

  • 类 class

作用:类是用于创建对象的模板。他们用代码封装数据以处理该数据。同时类声明也会引入一个新类型,并定义其字段方法构造函数

语法:class 类名(首字母大写(规范)){ 属性|方法 }

调用:const a : 类名 = new 类名

1.使用类创建对象:
class Person{            //定义类
name:string = '张三'
age:number = 18
}
let person1:Person = new Person() //实例化
//此时person1对象拥有2个属性name='张三',age=18
2.构造函数:
   class 类{
  字段A:类型
  字段B:类型

  constructor(参数...) {
// 通过 new 实例化的时候 会调用 constructor
// 通过关键字 this 可以获取到实例对象
  }
}
const 实例 = new 类()

作用:

一个类中一旦有了显式编写 constructor, 在new 类()的时候是可以传参的

这个参数是可以给类中的属性设置初始值,我们可以通过new 时传入不同的数据类决定创建什么样的对象

注意点

  1. 如果一个类中没有写constructor构造函数,类本身是有一个默认的没有带参数的构造函数
  2. 如果想要在new的时候带参数,则我们在定义类的时候,应该要显式编写constructor,参数类型和数量由我们自己定
  • new 和构造函数的关系

① 调new 的时候开辟一个内存空间 -> 写上类中的属性 此时没值

② 调用构造函数给属性赋值

③ 将创建好的对象返回交给我们定义的变量

image.png

3.实例方法:

类中可以定义实例方法,并且在内部编写逻辑。

class Person{       
constructor(name:string){
this.myname = name 
    }
sayHi(yourname:string){
console.log(`你好${yourname},我的名字是:${this.myname}`)
    }
}
const Hi:Person = new Person('Jack')
Hi.sayHi('Rose')

image.png

4.静态属性、方法

类还可以添加静态属性、方法,后续访问需要通过类来完成(一般在工具类中使用静态属性方法)

基本语法:

   // 定义
    class 类{
  static 字段:类型
  static 方法(){}
}

// 使用
类.字段
类.方法()

image.png (Math属性见下文)

5.继承

类可以通过 继承 快速获取另外一个类的 字段方法。 并且还可以扩展属于自己的字段和方法加强父类没有的能力

class 父类 {
  // 字段
  // 方法
  // 构造函数
}

class 子类 extends 父类{
  // 自己的字段(属性)
  // 自己的方法
  // 可以重写父类方法
}
6.修饰符

修饰符包括:readonly、private、protected和public。省略不写默认为 public

在类的属性或方法前加上readonly、private、protected即可

如: image.png

①当属性或方法前加上readonly(只读)时,外部只可取值不可修改

②当属性或方法前加上private(私有)时,不能在声明该属性或方法的类之外访问,包括子类。就像老婆是私有的不能共享一样😏

③当属性或方法前加上protected(受保护)时,类似private,但子类可以访问。就像你的财产,别人不能用,但你儿子可以使用🤪

④什么都没有添加时默认是public(公共)

  • 剩余和展开

1.剩余参数

语法:

 // 剩余参数只能写在最后一位
        function 函数名(参数1,参数2,...剩余参数数组){
          // 逻辑代码
          // 剩余参数之前的参数 挨个获取即可
          // 剩余参数:以数组的形式获取
        }

例:

image.png

2.展开

出于程序稳定性,以及运行性能考虑,在 ArkTS 中 ...(展开运算符) 只能用在数组上

const numArr1: number[] = [1, 2, 3, 4]
const numArr2: number[] = [5, 6, 7]

// 合并到一起
const totalArr: number[] = [...numArr1, ...numArr2]
//此时totalArr数组内为[1,2,3,4,5,6,7]
  • 接口补充

1.接口也可以继承,关键字:extends
interface 接口1{
  属性1:类型
}
interface 接口2 extends 接口1 {
  属性2:类型
}
2.接口实现(类来实现接口)

可以通过接口结合 implements 来限制 类 必须要有某些属性和方法

interface 接口{
  属性:类型
  方法:方法类型
}

classimplements 接口{
  // 必须实现 接口中定义的 属性、方法,否则会报错
}



  • Math对象

Math是一个内置对象,它拥有一些数学常数属性和数学函数方法。Math 的所有属性与方法都是静态的,使用的时候直接通过Math点出来即可

常用方法:

方法说明
Math.random()返回一个 0 到 1 之间的伪随机数。
Math.ceil(x)返回大于一个数的最小整数,即一个数向上取整后的值。
Math.floor(x)返回小于一个数的最大整数,即一个数向下取整后的值。
Math.round(x)返回四舍五入后的整数。
Math.abs(x)返回一个数的绝对值
Math.max([x[,y[, …]]])返回零到多个数值中最大值。
Math.min([x[,y[, …]]])返回零到多个数值中最小值。
  • 定时器

日常开发中如果需要代码 延迟一会执行,或者每隔一段时间执行一次,就可以使用定时器

1.setTimeout/clearTimeout
// setTimout会返回一个数字,表示当前延迟器的标记值
let 变量 = setTimeout(需要运行的函数,延迟时间单位毫秒)

//举例:
let timeId = setTimeout(()=>{
  console.log('我被执行了') // 只执行一次
} , 1000)

celarTimeout(timeId) //清除定时器(没有限制的话将不会执行setTimeout)

案例:

定时器.gif

示例代码:

@Entry
@Component
struct Index {

  @State opentb:number=400

  build() {
    Column(){
      Text('打开淘宝>')
        .backgroundColor(Color.Orange)
        .padding(5)
        .borderRadius(12)
        .position({x:this.opentb})

    }
    .height('100%')
    .width('100%')
    .onAppear(()=>{

      setTimeout(()=>{
        animateTo({},()=>{
          this.opentb=275
        })
      },2000)
    })
  }
}
2.setInterval/clearInterval

一般setInterval需要配合clearInterval一起使用,否则会一直执行占用内存。

clearInterval(setInterval的标记值)

//举例:
// 1. 创建定时器,使用timeId保存延迟器的标记值
let timeId = setTInterval(()=>{
  console.log('我被执行了')
} , 3000)

// 2. 清除定时器器的继续执行
clearInterval(timeId)

获取验证码案例:

yzm.gif

示例代码:

@Entry
@Component
struct Index {
  @State djs:number=0
  @State text:string = `发送验证码`
  timenum?:number
  build() {
    Column() {
      this.titleBuilder()
      TextInput({ placeholder: '请输入手机号' })
        .textInputExtend()
      Divider()
      Row() {
        TextInput({ placeholder: '请输入验证码' })
          .textInputExtend()
          .layoutWeight(1)
        Text(this.text)
          .fontSize(14)
          .fontColor(Color.Gray)
          .onClick(()=>{
            if(this.djs>0){
              return
            }

            let yzm = Math.floor(Math.random()*9000)+1000
            setTimeout(()=>{
              AlertDialog.show({message:yzm.toString()})
            },2000)
            this.djs=3
            this.timenum= setInterval(()=>{
              this.text=`${this.djs}秒后获取`
              this.djs--
              if (this.djs<=0){
                clearInterval(this.timenum)
                this.text='发送验证码'
              }
            },1000)


          })
      }
      .width('100%')

      Divider()

      Button('登录')
        .width('100%')
        .type(ButtonType.Normal)
        .backgroundColor('#ea6051')
        .margin({ top: 50 })

    }
    .padding({ top: 80, left: 40, right: 40 })
    .width('100%')
    .alignItems(HorizontalAlign.Start)
  }

  @Builder
  titleBuilder() {
    Text('短信登录')
      .fontSize(25)
      .fontWeight(600)
      .margin({ bottom: 30 })
  }
}

@Extend(TextInput)
function textInputExtend() {
  .backgroundColor(Color.White)
  .padding({ left: 0, top: 20, bottom: 20 })
  .placeholderColor('#ccc')
}
  • Date对象

    ArkTS 中另外一个常用的内置对象 Date,他可以用来创建、解析、操作日期和时间。

    使用 Date 对象首先需要通过 new 操作符进行实例化。

      // 获取当前日期
      const date1: Date = new Date()
      
      // 获取指定日期
      // ISO 8601 格式(YYYY-MM-DDTHH:mm:ss.ssZ)中间用 T 分隔
      const date2: Date = new Date('1995-01-01T01:11:00')
      
      // Unix时间戳 是指从1970年1月1日(UTC)开始到现在经历的时间(毫秒)
      const date3: Date = new Date(1706170405708)
    

常用方法:

方法名作用说明
getFullYear获取年份4 位数年份
getMonth获取月份取值 0-11
getDate获取日期月份中的日期
getHours获取小时
getMinutes获取分钟
getSeconds获取秒
getDay获取星期周日为 0

🔴注:获取月份比实际月份要小1,所以获取当前月份时需+1

时钟综合案例:

时钟.gif

示例代码:

@Entry
@Component
struct Index {
  // 1. 获取当前日期
  getNow() {
    let date = new Date()
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()

    return `${year}${month}${day}日`
  }

  // 2. 获取星期
  getWeek() {
    let date = new Date()
    let weekDay = date.getDay() // 周日为0
    let resWeek = ''
    switch (weekDay) {
      case 0:
        resWeek = '周日'
        break
      case 1:
        resWeek = '周一'
        break
      case 2:
        resWeek = '周二'
        break
      case 3:
        resWeek = '周三'
        break
      case 4:
        resWeek = '周四'
        break
      case 5:
        resWeek = '周五'
        break
      case 6:
        resWeek = '周六'
        break
      default:
    }

    return resWeek
  }

  // 3. 设置时钟时间变化
  @State hour: number = 0
  @State min: number = 0
  @State seconds: number = 0

  build() {
    Column() {
      Column() {
        Text(`${this.getNow()} ${this.getWeek()}`)
          .fontColor(Color.White)
          .fontSize(20)
        Stack() {
          Row({ space: 10 }) {
            Text(this.hour < 10 ? '0' + this.hour : this.hour.toString())       //判断是否为两位数
              .textStyle()
            Text(this.min < 10 ? '0' + this.min : this.min.toString())
              .textStyle()
            Text(this.seconds < 10 ? '0' + this.seconds : this.seconds.toString())
              .textStyle()
          }
          .onAppear(() => {
            // 3. 设置时钟时间变化
            setInterval(() => {
              let date = new Date()             
              this.hour = date.getHours()
              this.min = date.getMinutes()
              this.seconds = date.getSeconds()
            }, 1000)
          })

          Divider()
            .strokeWidth(2)
            .color(Color.Black)
        }
        .padding(10)

        Text('求知若渴,虚心若愚')
          .fontColor(Color.White)
          .fontSize(18)
      }

    }
    .width('100%')
    .height('100%')
    .backgroundColor(Color.Black)
    .justifyContent(FlexAlign.Center)
  }
}


@Extend(Text)
function textStyle() {
  .width(100)
  .height(100)
  .backgroundColor('#191919')
  .borderRadius(10)
  .textAlign(TextAlign.Center)
  .fontColor(Color.White)
  .fontSize(70)
  .fontWeight(900)
}
  • 字符串String

1.split()分隔
字符串.split(分隔符)// 返回切割之后的数组

需要一个变量来接收返回的数组

image.png

2.trim(去空格)

trim方法会从字符串的两端移除空白字符,并返回一个【新的字符串】,而不会修改原始字符串。

从上面图片中可以看出,输出的数组的每一个元素两侧都有空格,此时就需要去空格。

为了确定去空格了演示如下:

image.png

3.toLowerCase(转小写)和toUpperCase(转大写)
基本语法:
字符串.toLowerCase()// 返回转为小写之后的字符串
字符串.toUpperCase()// 返回转为大写之后的字符串

image.png

4. includes(判断是否存在)
基本语法:
字符串.includes(查询的字符串)// 返回判断结果 true / false

image.png

5.slice(提取)

slice方法提取字符串的一部分,并将其作为新字符串返回,而不修改原始字符串

基本语法:
字符串.slice(起始索引)// 从起始索引切割到末尾
字符串.slice(起始索引,结束索引) // 从起始索引,切换到结束索引

image.png

以上均为个人总结,如有不足请指出,谢谢!