1.Index.ets
// Index.ets
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
@State message: string = 'hhh'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
Divider()
Button(){
Text('change')
.fontSize(30)
}
.width('50%')
.onClick(()=>{
//建议方式
//因为this特殊性
this.message = 'new';
})
Button() {
Text('next')
.fontSize(30)
}
.margin({
top: 20
})
.width('50%')
.height('5%')
.onClick(this.next)
}
.width('100%')
}
.height('100%')
}
next(){
console.info('next click')
//second
//router.back()
router.pushUrl({url:'pages/Second'}).then(()=>{
console.info('next to')
}).catch( (err:BusinessError)=>{
console.error(
`jump second fail.code${err.code}.message${err.message}`
)
})
}
}
entry/src/main/resources/base/profile/main_pages.json
{
"src": [
"pages/Index",
"pages/Second"
]
}
2.@Builder装饰器->自定义构建函数/$$引用
// Index.ets
interface Label {
left:string
right:string
}
@Entry
@Component
struct Index {
@State msg:string = 'home'
build() {
Row() {
Column() {
Button() {
//点击事件$$变化时
//会触发UI刷新
this.ButtonText({left:'left',right:this.msg})
// GlobalText({left:'left',right:this.msg})
}
.onClick(()=>this.msg+='1')
}
.width('100%')
}
.height('100%')
}
@Builder
ButtonText($$:Label){
//$$能访问不能修改
Text($$.left+$$.right)
.fontSize(30)
}
}
//全局function
// @Builder
// function GlobalText($$:Label){
// Text($$.left+$$.right)
// .fontSize(30)
// }
3.TextInput
// Index.ets
interface Label {
label:string
}
@Entry
@Component
struct Index {
@State msg:string = 'home'
build() {
Row() {
Column() {
Button() {
GlobalText({label:this.msg})
}
TextInput({ text:this.msg })
.backgroundColor(Color.Orange)
.onChange((value)=>{
this.msg=value
})
}
.width('100%')
}
.height('100%')
}
}
@Builder
function GlobalText($$:Label){
Text($$.label)
.fontSize(30)
}
4.@Styles
@Entry
@Component
struct Index {
@State Width:number = 100
build() {
Row() {
Column() {
Button('1')
.putStyle()
Button('2')
.putStyle()
.inStyle()
}
.width('100%')
}
.height('100%')
}
@Styles
//@Styles仅支持通用属性
//不支持参数
inStyle(){
.width(this.Width)
}
}
@Styles
function putStyle(){
.backgroundColor(Color.Orange)
}
5.@Extend样式
@Entry
@Component
struct Index {
@State Width:number = 100
build() {
Row() {
Column() {
Button('test')
.ButtonColor(this.Width)
}
.width('100%')
}
.height('100%')
}
}
@Extend(Button)//只能全局
function ButtonColor(width:number){
.width(width)
.backgroundColor(Color.Orange)
}
6.stateStyles多态
@Entry
@Component
struct Index {
build() {
Row() {
Column() {
Button('button')
.stateStyles({
normal:{
.backgroundColor(Color.Red)
},
pressed:pressedStyle,
})
}
.width('100%')
}
.height('100%')
}
}
@Styles
function pressedStyle(){
.backgroundColor(Color.Orange)
}