HarmonyOS 鸿蒙Next 多个WrappedBuilder切换不起作用
HarmonyOS 鸿蒙Next 多个WrappedBuilder切换不起作用
@Builder
function test1(){
Text("test1")
}
@Builder
function test2(){
Text("test2")
}
@Builder
function test3(){
Text("test3")
}
@Component
struct TestComponent {
@State tests : WrappedBuilder<[]>[] = [
wrapBuilder(test1),
wrapBuilder(test2),
wrapBuilder(test3),
]
@State testIndex:number = 0;
build() {
Column(){
this.tests[this.testIndex].builder()
Text("点击我切换")
.onClick(()=>{
if ((this.testIndex + 1) >= this.tests.length) {
this.testIndex = 0;
}else {
this.testIndex ++;
}
console.log(`TestComponent testIndex:${this.testIndex}`)
})
}
}
}
5 回复
估计是状态变量的变化并不能驱动WrappedBuilder函数更新UI
我用foreach结合if,经测试后可以实现你要的功能
[@State](/user/State) index: number = 0
[@State](/user/State) b: WrappedBuilder<[]>[] = [wrapBuilder(tBuilder1), wrapBuilder(tBuilder2), wrapBuilder(tBuilder3)]
build() {
Column() {
ForEach(this.b, (item: WrappedBuilder<[]>, index: number) => {
if (this.index === index) {
item.builder()
}
})
Button("切换").onClick(() => {
this.index++;
// ...
})
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
哎 没有可以切换的容器,先这样搞
使用以下形式也不行
[@Builder](/user/Builder)
function test1(){
Text("test1")
}
[@Builder](/user/Builder)
function test2(){
Text("test2")
}
[@Builder](/user/Builder)
function test3(){
Text("test3")
}
[@Component](/user/Component)
struct TestComponent {
[@State](/user/State) tests : WrappedBuilder<[]>[] = [
wrapBuilder(test1),
wrapBuilder(test2),
wrapBuilder(test3),
]
[@State](/user/State) testIndex:number = 0;
build() {
Column(){
this.tests[this.testIndex].builder()
TestComponent1({test:this.tests[this.testIndex]})
Text("点击我切换")
.onClick(()=>{
if ((this.testIndex + 1) >= this.tests.length) {
this.testIndex = 0;
}else {
this.testIndex ++;
}
console.log(`TestComponent testIndex:${this.testIndex}`)
})
}
}
}
@Component
struct TestComponent1 {
@State test : WrappedBuilder<[]> | undefined = undefined
build() {
if (this.test!= undefined){
this.test.builder()
}
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
不能通过if判断是因为数组的设定是长度未知