問題1:100%寬度右邊超出范圍解決方式
使用Row寬度設置100%,當前Row設置外邊距或父組件設置外邊距或內邊距導致右邊內容超出范圍。
解決方式:使用Text.layoutWeight(1)占據Row里面剩余全部空間
問題2:橫向布局左邊高度跟隨右邊高度撐開
方式:動態高度計算(精準控制)
若右側內容高度動態變化需精準同步到左側,可以通過 自定義回調 或 彈性盒子監聽 動態設置左側組件高度。參考以下思路:
@Entry
@Component
struct DynamicHeightExample {
@State rightHeight: number = 0 // 綁定右側組件高度
build() {
Row() {
// 左側組件:高度綁定 rightHeight
Column() {
Text('左側內容')
}
.backgroundColor('#FF0000')
.height(this.rightHeight) // 動態綁定高度
// 右側組件:渲染完成后更新 rightHeight
Column() {
Text('右側動態高度內容,右側動態高度內容,右側動態高度內容,右側動態高度內容')
}
.backgroundColor('#0000FF')
.padding(10)
.onAreaChange((oldArea, newArea) => {
this.rightHeight = newArea.height // 監聽區域變化,更新左側高度
})
}
.width('100%')
}
}
問題3:在方法如何像自帶組件那樣使用{}傳參,不用按順序傳入
可以像 TextOptions 這樣把方法里面的入參封裝到interface或class里面
參考思路:
interface TextOptions {
controller: TextController;// 未加問號一定要傳的參數
text?: string;// 加問號非必傳的參數
}
問題4:HashMap不能直接使用中括號[],map['key']不能獲取和設置值,運行時會報錯
Error message:Cannot set property on Container
原因分析
- 與原生對象的機制不同
對象字面量({}):鍵會被轉換為字符串,且屬性直接掛在對象實例上,可通過obj[key]訪問。
Map類:內部通過get/set方法維護一個真正泛型的鍵值存儲,鍵可以是任意類型(如對象),不會被轉換為字符串屬性。 - 類型安全的強制要求
Map提供嚴格的泛型約束(如Map<string, number>),方法調用可確保類型的正確性。
若允許map[key]形式,會繞過TypeScript的類型檢查,增加潛在錯誤風險。
使用方式:
在ArkTS(或TypeScript)中,Map類型不直接支持方括號語法(如map['key'])訪問鍵值,而必須通過.get(key)和.set(key, value)方法
問題5:自定義彈窗如何解耦,脫離頁面@Component去使用
實現方式:可以抽離 @CustomDialog ,手動 new 一個 Component 組件,在組件里面去實現彈窗邏輯,
@Component
export struct DialogView {
showDialog(): CustomDialogController {
let dialogController = new CustomDialogController({
builder: CustomDialog(),
autoCancel: true,
alignment: DialogAlignment.Center,
offset: { dx: 0, dy: -20 },
customStyle: false,
backgroundColor: 0xd9ffffff,
cornerRadius: 10,
gridCount: 6
})
return dialogController
}
build() {
}
}
@Component
export struct Index {
dialog = new DialogView()
build() {
Text('顯示對話框').onClick(()=>{
dialog.showDialog()
})
}
}
還可以用promptAction.openCustomDialog,這個就能完全脫離了,直接靜態方法就可以顯示
import promptAction from '@ohos.promptAction'
let customDialogId: number = 0
@Builder
function customDialogBuilder(dialogTxt:string,index:string) {
TestDialog({ dialogTxt: dialogTxt,content:index })
}
@Component
struct TestDialog {
@State dialogTxt: string = ''
@State content: string = ''
build() {
Column() {
Text(this.dialogTxt+this.dialogTxt).fontSize(20)
Row() {
Button("確認").onClick(() => {
promptAction.closeCustomDialog(customDialogId)
})
Blank().width(50)
Button("取消").onClick(() => {
promptAction.closeCustomDialog(customDialogId)
})
}.margin({ top: 80 })
}.height(200).padding(5)
}
}
@Entry
@Component
struct Index {
@State message: string = '打開彈窗'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
promptAction.openCustomDialog({
builder: customDialogBuilder.bind(this, '標題','內容')// 重點,要把當前組件傳進去
}).then((dialogId: number) => {
customDialogId = dialogId
})
})
}
.width('100%')
}
.height('100%')
}
}
問題5:彈窗(Dialog)如何完全設置背景色透明
自定義彈窗(Dialog、CustomDialog)設置了背景色透明(backgroundColor: Color.Transparent),但是發現還有一層淡淡的蒙版。
解決方式:
// promptAction.openCustomDialog 彈窗方式
backgroundColor: Color.Transparent // 背景透明
maskColor: Color.Transparent // 蒙版透明,關鍵
// 或著
backgroundColor: Color.Transparent // 背景透明
isModal: false // 模態窗口有蒙層,非模態窗口無蒙層
// CustomDialogController 彈窗方式
backgroundColor: Color.Transparent // 背景透明
maskColor: Color.Transparent // 蒙版透明,關鍵
customStyle: true, // 啟用自定義樣式(避免系統默認約束),關鍵
// 或著
backgroundColor: Color.Transparent // 背景透明
isModal: false // 模態窗口有蒙層,非模態窗口無蒙層
customStyle: true, // 啟用自定義樣式(避免系統默認約束),關鍵
問題6:組件高度自適應,如何限制最大高度
方式:使用constraintSize方法可以設置約束尺寸,組件布局時,進行尺寸范圍限制。這里設置Scroll組件的高度限制。
Scroll() {
Column() {
if (this.wrapBuilder) {
// 創建自定義視圖
this.wrapBuilder.builder()
}
}.width('100%')
}.width('100%')
.constraintSize({maxHeight: 300})// 重點
問題7:Tabs根據官網示例做了指示器動畫,慢慢滑動會導致指示器先切換到目標在切回原來的tab
Tabs-導航與切換-ArkTS組件-ArkUI(方舟UI框架)-應用框架 - 華為HarmonyOS開發者
.onGestureSwipe((index: number, event: TabsAnimationEvent) => {
// 在頁面跟手滑動過程中,逐幀觸發該回調。
if (this.isSwitchTab) {
this.startAnimateTo(this.animationDuration, this.textInfos[this.curIndex][0], this.textInfos[this.curIndex][1])
return // tab已經切換停止
}
let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event)
this.currentIndex = currentIndicatorInfo.index
this.setIndicatorAttr(currentIndicatorInfo.left, currentIndicatorInfo.width)
})
isSwitchTab:boolean = false// 是否全換tab
private getCurrentIndicatorInfo(index: number, event: TabsAnimationEvent): Record<string, number> {
let nextIndex = index
if (index > 0 && event.currentOffset > 0)) {
nextIndex--
} else if (index < this.textInfos.length - 1 && event.currentOffset < 0)) {
nextIndex++
}
let indexInfo = this.textInfos[index]
let nextIndexInfo = this.textInfos[nextIndex]
let swipeRatio = Math.abs(event.currentOffset / this.tabsWidth)
let currentIndex = swipeRatio > 0.5 ? nextIndex : index // 頁面滑動超過一半,tabBar切換到下一頁。
isSwitchTab = true
let currentLeft = indexInfo[0] + (nextIndexInfo[0] - indexInfo[0]) * swipeRatio
let currentWidth = indexInfo[1] + (nextIndexInfo[1] - indexInfo[1]) * swipeRatio
return { 'index': currentIndex, 'left': currentLeft, 'width': currentWidth }
}
// 組件頂層監聽觸摸事件
.onTouch((event: TouchEvent) => {
if (event.type == TouchType.Up || event.type == TouchType.Cancel) {
this.isSwitchTab = false
}
})
問題8:ForEach、LazyForEach數據已刷新UI未更新問題
解決方式:手動設置keyGenerator內容,把會變動的值拼接成字符串返回,如下面源碼
注意:keyGenerator直接吧真個對象轉json使用的話會導致頁面卡頓
ForEach(this.vm.timeWatchList, (item: TestBean) => {
ListItem() {
TestCard({ timeWatch: item })
}
}, (item: TestBean, index: number) => item.value + '_' + index)
問題9:@Builder方法數據已刷新UI未更新問題
原因:@Builder存在兩個或者兩個以上參數,就算通過對象字面量的形式傳遞,值的改變也不會引起UI刷新。
@Builder只接受一個參數,當傳入一個參數的時候,通過對象字面量的形式傳遞,值的改變會引起UI的刷新。
// 未解決更新UI方式
this.tabText(0, `全部(${this.count})`)
@Builder
tabText(index: number, name: string) {
Text(name)
}
// 解決更新UI方式
this.tabText(0, `全部`)
@Builder
tabText(index: number, name: string) {
Text(`${this.name}(${this.count})`)
}
問題10:V2狀態管理,自定義組件數據已經刷新UI未更新問題
原因:接口返回的數據是JsonObject并不是真正我們想要的對象,然后里面就沒有對應注解,就會導致更新JsonObject里面的字段,對應UI不更新
解決方式:
- 自己創建一個就想要對象,再賦值
- 使用第三方SDK把JsonObject轉成想要的對象,如:class-transformer
具體可以參考下面代碼
import { JSON } from "@kit.ArkTS"
import { plainToInstance } from "class-transformer"
@ObservedV2
class TestBean {
@Trace test2: TestBean2 = new TestBean2()
}
@ObservedV2
class TestBean2 {
@Trace num: number = 0
}
@ComponentV2
export struct TestComponent {
test: TestBean = new TestBean()
build() {
Column() {
Button('new創建新對象-更新UI').onClick(() => {
// new出來TestBean2,所以更新UI
this.test.test2 = new TestBean2()
}).margin({ top: 100 })
Button('模擬接口創建新對象-不更新UI').onClick(() => {
// 其實還是個JsonObject對象,未真正轉成TestBean2,所以不更新UI
this.test.test2 = JSON.parse('{"num":-1}') as TestBean2
}).margin({ top: 10 })
Button('模擬接口創建新對象-更新UI').onClick(() => {
// 真正轉成TestBean2,所以更新UI
let test2 = plainToInstance(TestBean2,JSON.parse('{"num":-1}'))
this.test.test2 = test2
}).margin({ top: 10 })
Button('累加').onClick(() => {
this.test.test2.num++
}).margin({ top: 10 })
TestComponent2({ test2: this.test.test2, num: this.test.test2.num }).margin({ top: 10 })
}
.size({ width: '100%', height: '100%' })
}
}
@ComponentV2
export struct TestComponent2 {
@Param @Require test2: TestBean2
@Param num: number = 0
build() {
Column() {
Text(`測試:${this.num}`).margin({ top: 10 })
}
.size({ width: '100%', height: '100%' })
}
}