TypeScript基本语法:
变量声明
let 修饰变量
const修饰常量
//定义一个字符串类型
let msg: string = "123"
//定义数字类型,包括:整数、浮点数
let num: number = 12.9
//布尔类型
let boolValue: boolean = true
//可以定义任何类型
let a: any = 12
a = "12"
//可以取值规定的3种类型
let unionValue: string|number|boolean = "123"
unionValue = 299
//字典
let person = {name: 'Jack', age: 29}
console.log(msg, num, boolValue, a, unionValue, person.name)
//数组1
let array:Array<string> = ["123", "222"]
//数组2
let array2: number[] = [233, 222]
console.log(array[1])
console.log(array2[1])
在TypeScript里面,空字符串、数字0、null、undefined都被认为是false
跟OC一样,不用强制写false
条件语句
if-else以及switch语法,跟其他语法一样,不讲
for循环
对于for循环,有for-in和for-of两种方式:
for-in,取到的是index
for-of,取到的是元素
//数组1
let array:Array<string> = ["123", "222"]
//数组2
let array2: number[] = [233, 222]
for (const i in array){
console.log(i)//0,1
}
for (const i of array){
console.log(i)//233,222
}
函数
函数要以function开头,支持可选参数、默认参数、箭头函数等特殊语法
//sayHello 方法名
//name: string 参数以及参数类型
//: void 返回值类型
function sayHello(name: string): void{
console.log('你好' + name + '!')
}
//函数调用
sayHello("jack")
以上写法,可以修改为箭头函数
//函数也是一种类型,也就是函数是高阶函数,可以做参数、返回值
//let sayHello2 其实是: let sayHello2: 函数类型
let sayHello2 = (name: string) => {
console.log('你好2' + name + '!')
}
sayHello2("lili")
可选参数、默认参数
function sayHello3(name?: string){
name = name ? name : "陌生人"
console.log('你好3' + name + '!')
}
sayHello3("jack3")
sayHello3()
function sayHello4(name: string = "陌生人"){
console.log('你好4' + name + '!')
}
sayHello4("jack4")
sayHello4()
类和接口
TS具有面向对象的基本语法:interface、class、enum等,也具备封装、继承、多态
等面向对象的基本特征
有关:interface、class、enum
//定义枚举
enum Message {
//逗号隔开,且枚举被赋值
HI = 'hi',
HELLO = 'hello'
}
//定义一个接口A
interface A {
//接口里面的函数,不加function
say(message: Message):void
}
//实现接口
class B implements A {
//函数的实现
say(message: Message):void{
console.log(message + '123')
}
}
//创建一个类B,给a
let a1 = new B()
a1.say(Message.HI)
有关类、继承
//定义一个类
class Rectangle {
//成员变量
//不加let const
private width: number
private length: number
//构造函数
constructor(width: number, length: number) {
this.width = width
this.length = length
}
//成员方法,不用加function
public area(): number {
return this.width * this.length
}
}
//继承
class Square extends Rectangle{
constructor(side: number) {
//调用父类初始化方法
super(side, side)
}
}
//创建类Square
let s = new Square(10)
console.log("正方形的面积是:" + s.area())
UI组件学习
Image图片
图片加载方式:
网络图片
Image("图片地址")
.width(250)
.height(250)
在模拟器或真机上,需要在module.json5文件中添加网络权限:
"module": {
"requestPermissions": [//可以添加各种权限,是一个数组
{
//网络权限
"name": "ohos.permission.INTERNET"
}
],
}
本地加载
根据图片所在文件夹位置不同,分为:
Image($r('app.media.homeTophouse'))
Image($rawfile('homeTophouse.png'))
Text文本
Text(content?: string | Resource)
文本可以直接赋值字符串,这个好理解
也可以加载Resource本地文件内容
其实是为国际化做准备
可以在base-element下的string.json
和zh_CN-element下的string.json
以及en_US-element下的string.json
分别添加上不同的文字语言:
比如:
{
"string": [
{
"name": "label_width",
"value": "图片宽度:"
}
]
}
{
"string": [
{
"name": "label_width",
"value": "Image Width:"
}
]
}
TextInput输入文字
TextInput({placeholder?: string, text?: string})
TextInput({placeholder: "请输入文字", text: this.imageWidth.toFixed(0)})
.width(250)
.type(InputType.Number)
//监听文字的改变
.onChange(value => {
console.log(value)
this.imageWidth = parseInt(value)
})
字符串转数字:stringName.toFixed(0)
//0:保留0个小数
数字转字符串:parseInt(numName)
Button
Button("放大")
.width(100)
.type(ButtonType.Circle)
//点击事件
.onClick(() =>{
this.imageWidth *= 1.2;
})
或:
Button(){
Image($r("app.media.homeTophouse")).width(100).margin(25)
}
Slide
Slider({
min: 0,
max: 100,
//当前值
value: 50,
//步长
step: 10,
style: SliderStyle.OutSet,
direction: Axis.Horizontal,
reverse: false
})
.blockColor(Color.Green)
.width("90%")
.showTips(true)
.onChange(value => {
this.imageWidth = (500 * value)/100
console.log("1111118" + value)
})
页面布局
线性布局
column
容器:从上到下
row
容器:从左到右
space
: 子元素之间的间隔
column、row有两个轴:主轴、交叉轴
主轴:
属性名:justifyContent
作用:设置子元素在主轴
方向的对齐格式
取值:FlexAlign枚举,枚举取值及效果:
交叉轴:
属性名:alignItems
作用:设置子元素在交叉轴
方向的对齐格式
取值:column使用HorizontalAlign枚举、row使用VerticalAlign枚举
容器内边距:padding
组件外边距:margin
例子效果
import media from '@ohos.multimedia.media'
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
@State imageWidth: number = 250
build() {
Column({space: 20}) {
Row(){
Image("图片地址")
.width(this.imageWidth)
.height(this.imageWidth)
}
.width("100%")
.height(450)
.justifyContent(FlexAlign.Center)
Column(){
Row(){
Text($r("app.string.label_width"))
.fontSize(25)
.fontWeight(FontWeight.Regular)
.fontColor(Color.Gray)
TextInput({ placeholder: "请输入文字", text: this.imageWidth.toFixed(0) })
.width(150)
.backgroundColor("#FFF")
.type(InputType.Number)
.onChange(value => {
console.log(value)
this.imageWidth = parseInt(value)
})
}
.width("100%")
.justifyContent(FlexAlign.SpaceBetween)
Divider()
.width("100%")
}
Row(){
Button("缩小")
.width(80)
.type(ButtonType.Circle)
.onClick(() => {
this.imageWidth *= 0.8;
})
Button("放大")
.width(80)
.type(ButtonType.Circle)
.onClick(() => {
this.imageWidth *= 1.2;
})
// Button(){
// Image($r("app.media.homeTophouse")).width(100).margin(25)
// }
}
.width("100%")
.justifyContent(FlexAlign.SpaceAround)
Row(){
Slider({
min: 0,
max: 100,
//当前值
value: 50,
//步长
step: 10,
style: SliderStyle.OutSet,
direction: Axis.Horizontal,
reverse: false
})
.blockColor(Color.Green)
.width("90%")
.showTips(true)
.onChange(value => {
this.imageWidth = (500 * value)/100
console.log("1111118" + value)
})
//50%的时候是250
//100%的时候是500
}
.width("100%")
}
.width('100%')
.height('100%')
.padding({left: 30, right: 30})
}
}
渲染控制
当有列表的时候,可以使用ForEach
:循环遍历数组,根据数组内容渲染页面组件
import media from '@ohos.multimedia.media'
//model
class Item {
//String与string不一样
name: string
image: ResourceStr
price: number
//Number与number不一样
discount: number
constructor(name: string, image: ResourceStr, price: number, discount: number = 0) {
this.name = name;
this.image = image;
this.price = price;
this.discount = discount
}
}
@Entry
@Component
struct ItemPage {
//图片地址
private imageString = ""
//数据
private items: Array<Item> = [
new Item("华为P60", this.imageString, 30, 500),
new Item("华为P70", this.imageString, 130),
new Item("华为P80", this.imageString, 230),
new Item("华为P90", this.imageString, 290),
new Item("华为P100", this.imageString, 390),
new Item("华为P110", this.imageString, 490)
]
build() {
Column({space: 20}) {
Row(){
Text('商品列表')
.fontSize(25)
.fontWeight(FontWeight.Bolder)
.fontColor(Color.Black)
}
.width("100%")
.justifyContent(FlexAlign.Start)
.margin(20)
//列表渲染
ForEach(this.items, (item: Item) => {
Row(){
Image(item.image)
.width(80)
.height(80)
.borderRadius(5)
Column(){
//条件判断
if(item.discount){
Text(item.name)
.fontSize(15)
.fontWeight(FontWeight.Bolder)
.fontColor(Color.Black)
Text("原价:" + (item.price + item.discount))
.fontSize(15)
.fontWeight(FontWeight.Bolder)
.fontColor(Color.Gray)
.decoration({type: TextDecorationType.LineThrough})
Text("折扣价:" + item.price)
.fontSize(15)
.fontWeight(FontWeight.Bolder)
.fontColor(Color.Black)
Text("补贴:" + item.discount)
.fontSize(15)
.fontWeight(FontWeight.Bolder)
.fontColor(Color.Red)
}else{
Text(item.name)
.fontSize(15)
.fontWeight(FontWeight.Bolder)
.fontColor(Color.Black)
Text("¥" + item.price.toString())
.fontSize(15)
.fontWeight(FontWeight.Bolder)
.fontColor(Color.Red)
}
}
.justifyContent(FlexAlign.Start)
.alignItems(HorizontalAlign.Start)
.margin({left: 10})
}
.width("100%")
.height(100)
.justifyContent(FlexAlign.Start)
.backgroundColor("#FFF")
//圆角
.borderRadius(5)
})
}
.width('100%')
.height('100%')
.padding({left: 30, right: 30})
.backgroundColor("#D3D3D3")
}
}
List
上面的做法,当item太多的时候,不能滑动,因此,我们可以套一个list
List(){
ForEach(this.items, (item: Item) => {
ListItem(){
//里面只能有一个根元素
}
}
}
自定义组件
可以将某个组合组件提出来,封装成一个自定义组件,然后可以在本界面多出调用
也可以提出来,放在其他地方,这样其他地方也可以多出引用该自定义组件
自定义构建函数
首先,是一个函数,另外这个函数主要是做页面封装的函数
根据自定义构建函数位置不同,有不同的叫法:
首先,在当前组件的外面去写(也就是@Component
外面),被称为:全局自定义构造函数
,整个文件都可以使用
语法:
@Builder function Name(){
}
或者写到组件里面,被称为局部自定义构造函数
,语法:
function Name(){
}
自定义公共样式函数
可以将某些公共样式,抽出成函数,多出调用
样式以@Styles
开头的函数
举例:
@Styles function fileScreen(){
.width('100%')
.height('100%')
.padding({left: 30, right: 30})
.backgroundColor("#D3D3D3")
}
调用:.fileScreen()
@Styles
只能封装公共属性
除了抽多个组件共有的属性,也可以单独抽某一个组件单有的属性,比如文本的文字属性,但不能使用@Styles
,可以使用@Extend(组件类型)
:
@Extend(Text) function priceText(){
.fontSize(15)
.fontColor(Color.Black)
}
需要注意的是,@Extend
只能放在组件外部
状态管理
@State
@Prop和@Link
@Provide和@Consume
@Observed和@ObjectLink
这些都什么意思呢?一起来学习下吧