HarmonyOS 组件1--Button按钮组件
·
> Button组件声明语法
Button(label?:ResourceStr)
1. 文字型按钮
`Button('我是一个按钮')`
2. 自定义按钮 在按钮组件中嵌套其他组件
Button() { // 自定义的圆形搜索按钮
Image($r('app.media.search'))
.height(50)
.margin(10)
}
.type(ButtonType.Circle)

> 关于按钮的属性和方法
Button("跳转到界面2")
.width('80%') // 按钮的宽度
.height('8%') // 按钮的高度
.type(ButtonType.Normal)
// normal 普通按钮 circle 圆形按钮 capsule 胶囊型按钮(圆角默认为高度的一半)
.onClick(()=>{ // 点击处理事件
router.pushUrl({ // 跳转方法 -- 详情见下文
url:"pages/Index2" // 跳转的URL
})
})
一个跳转界面按钮的demo
Button("跳转到界面2") // 声明Button组件
.width('40%') // 设置宽度
.height('20%') // 设置高度
.onClick(()=>{ // 设置好点击事件
router.pushUrl({ // 这里跳转界面的逻辑与Flutter类似 采用路由跳转(需要加一个路由跳转的包)
url:"pages/Index2" // 添加跳转界面的Url(字符串格式)
})
})
注意:
跳转过去的界面,需要在main_page.json中声明
{
"src": [
"pages/Index",
"pages/Index2" // URL最好是把这个路径复制过去,不会出错,其他也可以保证正确就行
]
}
整体的demo
// index.ets
import router from '@ohos.router'
@Entry
@Component
struct Index {
@State message1: string = 'Harmony'
@State message2: string = '遥遥领先!'
build() {
Row() {
Column() {
Text(this.message1)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Text(this.message2)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button("跳转到界面2")
.width('80%')
.height('8%')
.onClick(()=>{
router.pushUrl({
url:"pages/Index2"
})
})
}
.width('100%')
}
.height('100%')
}
}
// index2.ets
import router from '@ohos.router'
@Entry
@Component
struct Index {
@State message1: string = '界面2'
@State message2: string = '遥遥领先!'
build() {
Row() {
Column() {
Text(this.message1)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Text(this.message2)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{ // 点击文字
router.back() // 跳转回到来时的界面
})
}
.width('100%')
}
.height('100%')
}
}
// main_pages.json json文件中不能有注释,复制的时候删掉这句注释!!!
{
"src": [
"pages/Index",
"pages/Index2"
]
}
> 两个按钮控制图片尺寸缩小放大
Row(){
Button('缩小')
// .width(100)
.height(60)
.type(ButtonType.Circle)
.onClick(()=>{
if (this.imageWidth>=10) {
this.imageWidth -= 10
}
})
Button('放大')
// .width(100)
.height(60)
.type(ButtonType.Circle)
.onClick(()=>{
// if (this.imageWidth<=360) {
// this.imageWidth += 10 // } // 也可以写三元表达式
this.imageWidth<=360?this.imageWidth+=10:this.imageWidth
})
}更多推荐



所有评论(0)