如何实现V1、V2版本之间父子组件的数据传递与共享
问题现象
场景一:如何实现V1版本组件向V2版本组件传递与共享数据?
场景二:如何实现V2版本组件向V1版本组件传递与共享数据?
背景知识
状态管理(V1):ArkUI状态管理V1提供了多种装饰器,通过使用这些装饰器,状态变量不仅可以观察组件内的改变,还可以在不同组件层级间传递,比如父子组件、跨组件层级,也可以观察全局范围内的变化。
状态管理(V2):为了增强状态管理V1版本的部分能力,例如深度观察、属性级更新等,ArkUI推出状态管理V2供开发者使用。
在实现V1、V2版本之间父子组件的数据传递与共享的功能前,应先了解V1、V2版本混用的规则:
API19前,详见官方文档状态管理V1和V2混用指导(API version 19前):概述、限制条件。
API19后,详见官方文档状态管理V1和V2混用指导(API version 19及之后):限制条件。
UIUtils.enableV2Compatibility:API19新增的方法,用于实现V1版本的数据可以在V2版本中使用的能力。若想要将V2版本的数据传递到V1版本的子组件,可以通过将V1版本的数据声明在V2版本的组件中,然后传递给V1版本的子组件使用。
解决方案
根据混用规则总结可实现的方案如下:
传递方向
API
方案
实现方式
V1->V2
API 19以后
使用UIUtils.enableV2Compatibility
在V1组件向V2组件传递参数时,通过UIUtils.enableV2Compatibility方法把V1的数据转化为能被V2装饰器@Param装饰器接收的数据。
API 19以前
使用AppStorage/AppStorageV2
使用AppStorageV2.connect传递。
使用参数传递
方式一:在V1组件内直接声明V2装饰器装饰的实例,不使用V1装饰器初始化,该实例可直接传递给V2版本的子组件。
方式二:创建一个不带任何装饰器装饰的类,内部再嵌套一个V2装饰器装饰的类。
方式三:在V1组件内通过V1版本装饰器声明的变量,在传递至V2版本的子组件时,用“{}”在外部构造为新的对象后,再传递给V2版本子组件。
V2->V1
API 19以后
使用UIUtils.enableV2Compatibility
在V2组件向V1组件传递参数时,通过UIUtils.enableV2Compatibility方法将V1版本@Observed装饰器装饰的类转化为能被@Local装饰器直接声明的数据。
API 19以前
使用AppStorage/AppStorageV2
使用AppStorageV2.connect传递。
使用参数传递
方式一:在V2组件内直接声明V1装饰器装饰的实例,不使用V2装饰器初始化,该实例可直接传递给V1版本的子组件。
方式二:创建一个不带任何装饰器装饰的类,内部再嵌套一个V2装饰器装饰的类。
方式三:在V2组件内通过V2版本装饰器声明的变量,在传递至V1版本的子组件时,用“{}”在外部构造为新的对象后,再传递给V1版本子组件。
场景一:实现V1版本组件向V2版本组件传递与共享数据。
方案一:API19及以后,使用UIUtils.enableV2Compatibility方法,详情参考官网链接:V1中使用V2的自定义组件。
方案二:全局获取方式,通过AppStorage/AppStorageV2实现,适用于API19以前,API19以后建议使用方案一。实现思路如下:
由于AppStorage中的@StorageLink只能在V1组件中使用,所以AppStorage在V1向V2传递的场景下,V2版本的子组件不能自动同步更新,只能通过AppStorage.get手动获取。建议通过AppStorageV2实现V1版本组件向V2版本组件传递与共享数据的功能。
在使用AppStorageV2时,可以搭配@ObservedV2/@Trace实现深度观测。
由于AppStorageV2和@ObservedV2/@Trace是V2版本的装饰器,所以他们修饰的数据在V1子组件内初始化时,不能用V1的装饰器装饰。
完整示例代码如下:
import { AppStorageV2 } from '@kit.ArkUI';
@ObservedV2
class V1ToV2ExampleTwo {
@Trace text: string = '1';
constructor(text: string) {
this.text = text;
}
}
@Entry
@Component
struct V1ToV2Two {
exampleAppStorageV2: V1ToV2ExampleTwo =
AppStorageV2.connect<V1ToV2ExampleTwo>(V1ToV2ExampleTwo, () => new V1ToV2ExampleTwo('1'))!; // 不可直接使用V1装饰器装饰
build() {
Column({ space: 10 }) {
Text(V1父组件,AppStorageV2:${this.exampleAppStorageV2.text});
Button('V1 中修改')
.onClick(() => {
this.exampleAppStorageV2.text += '1';
});
Column() {
}
.height(50);
V1ToV2TwoChild();
}.width('100%');
}
}
@ComponentV2
struct V1ToV2TwoChild {
@Local exampleAppStorageV2: V1ToV2ExampleTwo =
AppStorageV2.connect<V1ToV2ExampleTwo>(V1ToV2ExampleTwo, () => new V1ToV2ExampleTwo('1'))!;
build() {
Column({ space: 10 }) {
Text(V2子组件,AppStorageV2:${this.exampleAppStorageV2.text});
Button('V2 中修改')
.onClick(() => {
this.exampleAppStorageV2.text += '1';
});
};
}
}
实现效果如下:
点击放大
方案三:传参方式,该方案一共三种传递形式,适用于API19以前,API19以后建议使用方案一。
该场景下由于@Observed/@ObjectLink装饰器需要搭配使用,但是V2版本的子组件不能使用@ObjectLink装饰器,所以该场景下,不建议使用@Observed装饰器装饰的类作为传递的参数。使用ObservedV2/@Trace装饰器装饰的类,作为传递的参数。实现思路如下:
方式一:在V1组件内直接声明V2装饰器装饰的实例,不使用V1装饰器初始化,该实例可直接传递给V2版本的子组件。
方式二:创建一个不带任何装饰器装饰的类,内部再嵌套一个V2装饰器装饰的类,就可以实现在V1组件内用V1装饰器实例化该嵌套类。传递给V2版本的子组件时,将该嵌套对象内部的对象单独传递给V2版本的子组件即可。
方式三:在V1组件内通过V1版本装饰器声明的变量,在传递至V2版本的子组件时,用“{}”在外部构造为新的对象后,就可以允许传递给V2版本子组件。
注意
若方式三在V1组件内通过V1版本装饰器声明的变量是简单类型如string、number等,要实现在子组件中能修改父组件的变量,需要在父组件内实现一个修改该变量的函数,传递给子组件。子组件通过@Event接收,需要修改时直接调用该函数即可。
若方式三传递的是对象,由于@ObservedV2/@Trace装饰器装饰的类不能在V1组件内用V1版本的装饰器初始化,所以需要创建一个不带装饰器的类,然后才能用V1装饰器在V1组件内初始化。
完整示例代码如下:
@ObservedV2
class V1ToV2ExampleThreeV2 {
@Trace text: string = '1';
constructor(text: string) {
this.text = text;
}
}
class V1ToV2ExampleThree {
text: string = '1';
constructor(text: string) {
this.text = text;
}
}
class V1ToV2ExampleThreeFather {
example: V1ToV2ExampleThreeV2 = new V1ToV2ExampleThreeV2('1');
}
interface V1ToV2ExampleThreeFace {
text: string;
}
interface V1ToV2ExampleThreeFatherFace {
example: V1ToV2ExampleThree;
}
@Entry
@Component
struct V1ToV2Three {
// 方式一,不使用V1装饰器在V1组件内初始化V2装饰器@ObservedV2/@Trace装饰的类
exampleOne: V1ToV2ExampleThreeV2 = new V1ToV2ExampleThreeV2('1');
// 方式二,将V2装饰器@ObservedV2/@Trace装饰的类嵌套进不带任何装饰器装饰的类里,再进行初始化
@State exampleTwo: V1ToV2ExampleThreeFather = new V1ToV2ExampleThreeFather();
// 方式三,传递简单类型
@State text: string = '1';
// 方式三,传递对象
@State exampleThreeChange: V1ToV2ExampleThree = new V1ToV2ExampleThree('1');
build() {
Column({ space: 10 }) {
Text(V1父组件,方式一,参数传递:${this.exampleOne.text});
Text(V1父组件,方式二,参数传递:${this.exampleTwo.example.text});
Text(V1父组件,方式三,简单类型参数传递:${this.text});
Text(V1父组件,方式三,对象参数传递:${this.exampleThreeChange.text});
Button('V1 中修改')
.onClick(() => {
// 方式一,数据在V1子组件中修改方式
this.exampleOne.text += '1';
// 方式二,数据在V1子组件中修改方式
this.exampleTwo.example.text += '1';
// 方式三,传递简单类型在V1子组件中修改方式
this.text += '1';
// 方式三,传递对象在V1子组件中修改方式
this.exampleThreeChange.text += '1';
});
Column() {
}
.height(20);
V1ToV2ThreeChild({
// 方式一,可直接传递
exampleOne: this.exampleOne,
// 方式二,需要传递的数据为属性
exampleTwo: this.exampleTwo.example,
// 方式三,将字符串作为对象的属性传递
exampleThree: {
text: this.text
},
changeText: () => {
this.text += '1';
},
// 方式三,将声明的对象作为属性传递
exampleThreeChange: {
example: this.exampleThreeChange
}
});
}.width('100%');
}
}
@ComponentV2
struct V1ToV2ThreeChild {
// 方式一接收的数据
@Param @Require exampleOne: V1ToV2ExampleThreeV2;
// 方式二接收的数据
@Param @Require exampleTwo: V1ToV2ExampleThreeV2;
// 方式三(传递简单类型)接收的数据
@Param @Require exampleThree: V1ToV2ExampleThreeFace;
// 父组件传递的是简单类型变量时必备,不然无法同步修改父组件字符串内容
@Event changeText: () => void = () => {
};
// 方式三(传递对象)接收的数据
@Param @Require exampleThreeChange: V1ToV2ExampleThreeFatherFace;
build() {
Column({ space: 10 }) {
Text(V2子组件,方式一,参数传递:${this.exampleOne.text});
Text(V2子组件,方式二,参数传递:${this.exampleTwo.text});
Text(V2子组件,方式三,简单类型参数传递:${this.exampleThree.text});
Text(V2子组件,方式三,对象参数传递:${this.exampleThreeChange.example.text});
Button('V2 中修改')
.onClick(() => {
// 方式一,数据在V2子组件中修改方式
this.exampleOne.text += '1';
// 方式二,数据在V2子组件中修改方式
this.exampleTwo.text += '1';
// 方式三,传递简单类型在V2子组件中修改方式
this.changeText();
// 方式三,传递对象在V2子组件中修改方式
this.exampleThreeChange.example.text += '1';
});
};
}
}
实现效果如下:
点击放大
场景二:实现V2版本组件向V1版本组件传递与共享数据。
方案一:API19之后,使用UIUtils.enableV2Compatibility方法,详情可参考官网链接:V2中使用V1的自定义组件。
方案二:全局获取方式,通过AppStorage/AppStorageV2实现,适用于API19以前,API19以后建议使用方案一。
该方案与场景一中方案二实现思路基本一致,额外补充如下:
V2版本的父组件不能通过AppStorage中的@StorageLink自动同步刷新,只能通过AppStorage.get手动获取,建议通过AppStorageV2实现。
完整示例代码如下:
import { AppStorageV2 } from '@kit.ArkUI';
@ObservedV2
class V2ToV1ExampleTwoV2 {
@Trace text: string = '1';
constructor(text: string) {
this.text = text;
}
}
@Entry
@ComponentV2
struct V2ToV1Two {
@Local exampleAppStorageV2: V2ToV1ExampleTwoV2 =
AppStorageV2.connect<V2ToV1ExampleTwoV2>(V2ToV1ExampleTwoV2, () => new V2ToV1ExampleTwoV2('1'))!;
build() {
Column({ space: 10 }) {
Text(V2父组件,AppStorageV2:${this.exampleAppStorageV2.text});
Button('V2 中修改')
.onClick(() => {
this.exampleAppStorageV2.text += '1';
});
Column() {
}
.height(50);
V2ToV1TwoChild();
}.width('100%');
}
}
@Component
struct V2ToV1TwoChild {
exampleAppStorageV2: V2ToV1ExampleTwoV2 =
AppStorageV2.connect<V2ToV1ExampleTwoV2>(V2ToV1ExampleTwoV2, () => new V2ToV1ExampleTwoV2('1'))!; // 不可直接使用V1装饰器装饰
build() {
Column({ space: 10 }) {
Text(V1子组件,AppStorageV2:${this.exampleAppStorageV2.text});
Button('V1 中修改')
.onClick(() => {
this.exampleAppStorageV2.text += '1';
});
};
}
}
实现效果如下:
点击放大
方案三:传参方式,适用于API19以前,API19以后建议使用方案一。
该方案与场景一中方案三实现思路基本一致,额外补充如下:
该场景下V2组件作为父组件,V1组件作为子组件。@ObjectLink装饰器可以在V1子组件内使用,所以传递的参数既可以是@Observed装饰器装饰的类,也可以是@ObservedV2/@Trace装饰器装饰的类(@ObservedV2/@Trace装饰器的场景参考下文“方式三,对象参数传递”的场景)。
V2组件作为子组件时,只能通过@Param装饰器接收参数,但是当V1组件作为子组件时,可以通过@Prop、@ObjectLink、@Link三种装饰器接收参数。但是根据知识背景中的混用校验规则,@Link只能被V1状态变量初始化,详情见@Link变量的传递/访问规则说明,所以使用@Prop、@ObjectLink接收V2父组件传递来的参数。
在实现“方式三,对象参数传递”的场景时,由于@ObservedV2/@Trace装饰的类可以直接在V2组件内声明,所以将@ObservedV2/@Trace装饰的类实例化后作为属性传递即可。
完整示例代码如下:
@Observed
class V2ToV1ExampleThreeV1 {
text: string = '1';
constructor(text: string) {
this.text = text;
}
}
class V2ToV1ExampleThreeFather {
example: V2ToV1ExampleThreeV1 = new V2ToV1ExampleThreeV1('1');
}
@ObservedV2
class V2ToV1ExampleThreeV2 {
@Trace text: string = '1';
constructor(text: string) {
this.text = text;
}
}
interface V2ToV1ExampleThreeFatherV2Face {
example: V2ToV1ExampleThreeV2;
}
interface V2ToV1ExampleThreeFace {
text: string;
}
@Entry
@ComponentV2
struct V2ToV1Three {
// 方式一,不使用V2装饰器在V2组件内初始化V1装饰器@Observed装饰的类
exampleOne: V2ToV1ExampleThreeV1 = new V2ToV1ExampleThreeV1('1');
// 方式二,将V1装饰器@Observed装饰的类嵌套进不带任何装饰器装饰的类里,再进行初始化
@Local exampleTwo: V2ToV1ExampleThreeFather = new V2ToV1ExampleThreeFather();
// 方式三,传递简单类型
@Local text: string = '1';
// 方式三,@ObservedV2装饰的类的实例化后传递
@Local exampleFour: V2ToV1ExampleThreeV2 = new V2ToV1ExampleThreeV2('1');
build() {
Column({ space: 10 }) {
Text(V2父组件,方式一,参数传递:${this.exampleOne.text}); // 不刷新
Text(V2父组件,方式二,参数传递:${this.exampleTwo.example.text}); // 不刷新
Text(V2父组件,方式三,简单类型参数传递:${this.text}); // 刷新
Text(V2父组件,方式三,对象参数传递:${this.exampleFour.text}); // 刷新
Button('V2 中修改')
.onClick(() => {
// 方式一,数据在V2父组件中修改方式
this.exampleOne.text += '1';
// 方式二,数据在V2父组件中修改方式
this.exampleTwo.example.text += '1';
// 方式三,传递简单类型在V2父组件中修改方式
this.text += '1';
// 方式三,传递@ObservedV2装饰的对象在V2父组件中修改方式
this.exampleFour.text += '1';
});
Column() {
}
.height(20);
V2ToV1ThreeChild({
// 方式一,可直接传递
exampleOne: this.exampleOne,
// 方式二,传递的是封装后的属性
exampleTwo: this.exampleTwo.example,
// 方式三,将字符串作为对象的属性传递
exampleThree: {
text: this.text
},
changeText: () => {
this.text += '1';
},
// 方式三,将声明的@ObservedV2装饰的对象作为属性传递
exampleFour: {
example: this.exampleFour
}
});
}.width('100%');
}
}
@Component
struct V2ToV1ThreeChild {
// 方式一接收的数据
@Prop exampleOne: V2ToV1ExampleThreeV1;
// 方式二接受的数据
@ObjectLink exampleTwo: V2ToV1ExampleThreeV1;
// 方式三(传递简单类型)接收的数据
@Prop exampleThree: V2ToV1ExampleThreeFace;
// 父组件传递的是简单类型变量时必备,不然无法同步修改父组件字符串内容
changeText: () => void = () => {
};
// 方式三(传递对象)接收的数据
@ObjectLink exampleFour: V2ToV1ExampleThreeFatherV2Face;
build() {
Column({ space: 10 }) {
Text(V1子组件,方式一,参数传递:${this.exampleOne.text});
Text(V1子组件,方式二,参数传递:${this.exampleTwo.text});
Text(V1子组件,方式三,简单类型参数传递:${this.exampleThree.text});
Text(V1子组件,方式三,对象参数传递:${this.exampleFour.example.text});
Button('V1 中修改')
.onClick(() => {
// 方式一,数据在V1子组件中修改方式
this.exampleOne.text += '1';
// 方式二,数据在V1子组件中修改方式
this.exampleTwo.text += '1';
// 方式三,传递简单类型在V1子组件中修改方式
this.changeText();
// 方式三,传递对象在V1子组件中修改方式
this.exampleFour.example.text += '1';
});
};
}
}
实现效果如下:
点击放大
注意
@Observed/@ObjectLink可以实现父组件修改深层属性后,刷新子组件对应属性绑定的UI的功能,但是当子组件内修改深层属性,父组件并不会刷新对应属性绑定的UI。所以除了通过方式三以外的方式一、方式二不会刷新父组件绑定的对应属性的UI。
常见FAQ
Q:使用Navigation导航的应用在V1版本中用的是@Provide/@Consume装饰器传递的NavPathStack路由栈。在V1迁移V2过程中,Navigation主页被修改为V2版本,子页依旧是保持的V1版本。此时应该怎样传递NavPathStack路由栈给子页面?
A:由于@ComponentV2内不能使用V1版本的@Provide/@Consume装饰器,@Component内不能使用V2版本的@Provider/@Consumer装饰器,所以当父子组件分别属于V1、V2版本时,不能使用@Provider/@Consumer、@Provide/@Consume去实现组件见页面的共享与数据传递。可参考解决方案如下:
使用AppStorage存储或者获取数据:在Navigation主页面通过AppStorage.setOrCreate进行全局存储,在V1版本的NavDestination子页面内直接通过@StorageLink进行全局路由栈获取。
使用AppStorageV2存储或者获取数据:分别在父组件与子组件通过pathStack: NavPathStack = AppStorageV2.connect(NavPathStack, () => new NavPathStack())!;创建或获取全局路由栈。
如果页面中使用了NavDestination组件,可以通过onReady事件获取路由栈:.onReady((context: NavDestinationContext) => {this.pathInfos = context.pathStack}),从而避免状态管理版本冲突的问题。
通过自定义组件查询接口获取,也可以避免状态管理传递冲突的问题,参考queryNavigationInfo。
Q:在V1迁移V2的过程中,存在部分三方库是V1版本实现,还没适配V2版本,应该如何将V2版本的数据传递给V1版本三方库?
A:建议参考场景二中方案一,方案三实现。该场景下,方案二AppStorageV2.connect没办法写进三方库内。
总结
在API19之后,优先推荐使用官方提供的UIUtils.enableV2Compatibility方法实现V1、V2版本之间父子组件的数据传递与共享。
https://coub.com/view/4b707t
https://coub.com/view/4b707r
https://coub.com/view/4b707o
https://coub.com/view/4b707n
https://coub.com/view/4b707h
https://coub.com/view/4b707d
https://coub.com/view/4b7077
https://coub.com/view/4b7074
https://coub.com/view/4b706z
https://coub.com/view/4b706u
https://coub.com/view/4b706o
https://coub.com/view/4b706c
https://coub.com/view/4b7063
https://coub.com/view/4b7060
https://coub.com/view/4b705v
https://coub.com/view/4b705n
https://coub.com/view/4b705k
https://coub.com/view/4b701z
https://coub.com/view/4b6zjc
https://coub.com/view/4b6zja
https://coub.com/view/4b6zj9
https://coub.com/view/4b6zj6
https://coub.com/view/4b6zj4
https://coub.com/view/4b6zj3
https://coub.com/view/4b6zj2
https://coub.com/view/4b6zj1
https://coub.com/view/4b6ziz
https://coub.com/view/4b6zix
https://coub.com/view/4b6ziv
https://coub.com/view/4b6ziu
https://coub.com/view/4b6zit
https://coub.com/view/4b6zis
https://coub.com/view/4b6zio
https://coub.com/view/4b6zin
https://coub.com/view/4b6zim
https://coub.com/view/4b6zik
问题现象
场景一:如何实现V1版本组件向V2版本组件传递与共享数据?
场景二:如何实现V2版本组件向V1版本组件传递与共享数据?
背景知识
状态管理(V1):ArkUI状态管理V1提供了多种装饰器,通过使用这些装饰器,状态变量不仅可以观察组件内的改变,还可以在不同组件层级间传递,比如父子组件、跨组件层级,也可以观察全局范围内的变化。
状态管理(V2):为了增强状态管理V1版本的部分能力,例如深度观察、属性级更新等,ArkUI推出状态管理V2供开发者使用。
在实现V1、V2版本之间父子组件的数据传递与共享的功能前,应先了解V1、V2版本混用的规则:
API19前,详见官方文档状态管理V1和V2混用指导(API version 19前):概述、限制条件。
API19后,详见官方文档状态管理V1和V2混用指导(API version 19及之后):限制条件。
UIUtils.enableV2Compatibility:API19新增的方法,用于实现V1版本的数据可以在V2版本中使用的能力。若想要将V2版本的数据传递到V1版本的子组件,可以通过将V1版本的数据声明在V2版本的组件中,然后传递给V1版本的子组件使用。
解决方案
根据混用规则总结可实现的方案如下:
传递方向
API
方案
实现方式
V1->V2
API 19以后
使用UIUtils.enableV2Compatibility
在V1组件向V2组件传递参数时,通过UIUtils.enableV2Compatibility方法把V1的数据转化为能被V2装饰器@Param装饰器接收的数据。
API 19以前
使用AppStorage/AppStorageV2
使用AppStorageV2.connect传递。
使用参数传递
方式一:在V1组件内直接声明V2装饰器装饰的实例,不使用V1装饰器初始化,该实例可直接传递给V2版本的子组件。
方式二:创建一个不带任何装饰器装饰的类,内部再嵌套一个V2装饰器装饰的类。
方式三:在V1组件内通过V1版本装饰器声明的变量,在传递至V2版本的子组件时,用“{}”在外部构造为新的对象后,再传递给V2版本子组件。
V2->V1
API 19以后
使用UIUtils.enableV2Compatibility
在V2组件向V1组件传递参数时,通过UIUtils.enableV2Compatibility方法将V1版本@Observed装饰器装饰的类转化为能被@Local装饰器直接声明的数据。
API 19以前
使用AppStorage/AppStorageV2
使用AppStorageV2.connect传递。
使用参数传递
方式一:在V2组件内直接声明V1装饰器装饰的实例,不使用V2装饰器初始化,该实例可直接传递给V1版本的子组件。
方式二:创建一个不带任何装饰器装饰的类,内部再嵌套一个V2装饰器装饰的类。
方式三:在V2组件内通过V2版本装饰器声明的变量,在传递至V1版本的子组件时,用“{}”在外部构造为新的对象后,再传递给V1版本子组件。
场景一:实现V1版本组件向V2版本组件传递与共享数据。
方案一:API19及以后,使用UIUtils.enableV2Compatibility方法,详情参考官网链接:V1中使用V2的自定义组件。
方案二:全局获取方式,通过AppStorage/AppStorageV2实现,适用于API19以前,API19以后建议使用方案一。实现思路如下:
由于AppStorage中的@StorageLink只能在V1组件中使用,所以AppStorage在V1向V2传递的场景下,V2版本的子组件不能自动同步更新,只能通过AppStorage.get手动获取。建议通过AppStorageV2实现V1版本组件向V2版本组件传递与共享数据的功能。
在使用AppStorageV2时,可以搭配@ObservedV2/@Trace实现深度观测。
由于AppStorageV2和@ObservedV2/@Trace是V2版本的装饰器,所以他们修饰的数据在V1子组件内初始化时,不能用V1的装饰器装饰。
完整示例代码如下:
import { AppStorageV2 } from '@kit.ArkUI';
@ObservedV2
class V1ToV2ExampleTwo {
@Trace text: string = '1';
constructor(text: string) {
this.text = text;
}
}
@Entry
@Component
struct V1ToV2Two {
exampleAppStorageV2: V1ToV2ExampleTwo =
AppStorageV2.connect<V1ToV2ExampleTwo>(V1ToV2ExampleTwo, () => new V1ToV2ExampleTwo('1'))!; // 不可直接使用V1装饰器装饰
build() {
Column({ space: 10 }) {
Text(V1父组件,AppStorageV2:${this.exampleAppStorageV2.text});
Button('V1 中修改')
.onClick(() => {
this.exampleAppStorageV2.text += '1';
});
Column() {
}
.height(50);
V1ToV2TwoChild();
}.width('100%');
}
}
@ComponentV2
struct V1ToV2TwoChild {
@Local exampleAppStorageV2: V1ToV2ExampleTwo =
AppStorageV2.connect<V1ToV2ExampleTwo>(V1ToV2ExampleTwo, () => new V1ToV2ExampleTwo('1'))!;
build() {
Column({ space: 10 }) {
Text(V2子组件,AppStorageV2:${this.exampleAppStorageV2.text});
Button('V2 中修改')
.onClick(() => {
this.exampleAppStorageV2.text += '1';
});
};
}
}
实现效果如下:
点击放大
方案三:传参方式,该方案一共三种传递形式,适用于API19以前,API19以后建议使用方案一。
该场景下由于@Observed/@ObjectLink装饰器需要搭配使用,但是V2版本的子组件不能使用@ObjectLink装饰器,所以该场景下,不建议使用@Observed装饰器装饰的类作为传递的参数。使用ObservedV2/@Trace装饰器装饰的类,作为传递的参数。实现思路如下:
方式一:在V1组件内直接声明V2装饰器装饰的实例,不使用V1装饰器初始化,该实例可直接传递给V2版本的子组件。
方式二:创建一个不带任何装饰器装饰的类,内部再嵌套一个V2装饰器装饰的类,就可以实现在V1组件内用V1装饰器实例化该嵌套类。传递给V2版本的子组件时,将该嵌套对象内部的对象单独传递给V2版本的子组件即可。
方式三:在V1组件内通过V1版本装饰器声明的变量,在传递至V2版本的子组件时,用“{}”在外部构造为新的对象后,就可以允许传递给V2版本子组件。
注意
若方式三在V1组件内通过V1版本装饰器声明的变量是简单类型如string、number等,要实现在子组件中能修改父组件的变量,需要在父组件内实现一个修改该变量的函数,传递给子组件。子组件通过@Event接收,需要修改时直接调用该函数即可。
若方式三传递的是对象,由于@ObservedV2/@Trace装饰器装饰的类不能在V1组件内用V1版本的装饰器初始化,所以需要创建一个不带装饰器的类,然后才能用V1装饰器在V1组件内初始化。
完整示例代码如下:
@ObservedV2
class V1ToV2ExampleThreeV2 {
@Trace text: string = '1';
constructor(text: string) {
this.text = text;
}
}
class V1ToV2ExampleThree {
text: string = '1';
constructor(text: string) {
this.text = text;
}
}
class V1ToV2ExampleThreeFather {
example: V1ToV2ExampleThreeV2 = new V1ToV2ExampleThreeV2('1');
}
interface V1ToV2ExampleThreeFace {
text: string;
}
interface V1ToV2ExampleThreeFatherFace {
example: V1ToV2ExampleThree;
}
@Entry
@Component
struct V1ToV2Three {
// 方式一,不使用V1装饰器在V1组件内初始化V2装饰器@ObservedV2/@Trace装饰的类
exampleOne: V1ToV2ExampleThreeV2 = new V1ToV2ExampleThreeV2('1');
// 方式二,将V2装饰器@ObservedV2/@Trace装饰的类嵌套进不带任何装饰器装饰的类里,再进行初始化
@State exampleTwo: V1ToV2ExampleThreeFather = new V1ToV2ExampleThreeFather();
// 方式三,传递简单类型
@State text: string = '1';
// 方式三,传递对象
@State exampleThreeChange: V1ToV2ExampleThree = new V1ToV2ExampleThree('1');
build() {
Column({ space: 10 }) {
Text(V1父组件,方式一,参数传递:${this.exampleOne.text});
Text(V1父组件,方式二,参数传递:${this.exampleTwo.example.text});
Text(V1父组件,方式三,简单类型参数传递:${this.text});
Text(V1父组件,方式三,对象参数传递:${this.exampleThreeChange.text});
Button('V1 中修改')
.onClick(() => {
// 方式一,数据在V1子组件中修改方式
this.exampleOne.text += '1';
// 方式二,数据在V1子组件中修改方式
this.exampleTwo.example.text += '1';
// 方式三,传递简单类型在V1子组件中修改方式
this.text += '1';
// 方式三,传递对象在V1子组件中修改方式
this.exampleThreeChange.text += '1';
});
Column() {
}
.height(20);
V1ToV2ThreeChild({
// 方式一,可直接传递
exampleOne: this.exampleOne,
// 方式二,需要传递的数据为属性
exampleTwo: this.exampleTwo.example,
// 方式三,将字符串作为对象的属性传递
exampleThree: {
text: this.text
},
changeText: () => {
this.text += '1';
},
// 方式三,将声明的对象作为属性传递
exampleThreeChange: {
example: this.exampleThreeChange
}
});
}.width('100%');
}
}
@ComponentV2
struct V1ToV2ThreeChild {
// 方式一接收的数据
@Param @Require exampleOne: V1ToV2ExampleThreeV2;
// 方式二接收的数据
@Param @Require exampleTwo: V1ToV2ExampleThreeV2;
// 方式三(传递简单类型)接收的数据
@Param @Require exampleThree: V1ToV2ExampleThreeFace;
// 父组件传递的是简单类型变量时必备,不然无法同步修改父组件字符串内容
@Event changeText: () => void = () => {
};
// 方式三(传递对象)接收的数据
@Param @Require exampleThreeChange: V1ToV2ExampleThreeFatherFace;
build() {
Column({ space: 10 }) {
Text(V2子组件,方式一,参数传递:${this.exampleOne.text});
Text(V2子组件,方式二,参数传递:${this.exampleTwo.text});
Text(V2子组件,方式三,简单类型参数传递:${this.exampleThree.text});
Text(V2子组件,方式三,对象参数传递:${this.exampleThreeChange.example.text});
Button('V2 中修改')
.onClick(() => {
// 方式一,数据在V2子组件中修改方式
this.exampleOne.text += '1';
// 方式二,数据在V2子组件中修改方式
this.exampleTwo.text += '1';
// 方式三,传递简单类型在V2子组件中修改方式
this.changeText();
// 方式三,传递对象在V2子组件中修改方式
this.exampleThreeChange.example.text += '1';
});
};
}
}
实现效果如下:
点击放大
场景二:实现V2版本组件向V1版本组件传递与共享数据。
方案一:API19之后,使用UIUtils.enableV2Compatibility方法,详情可参考官网链接:V2中使用V1的自定义组件。
方案二:全局获取方式,通过AppStorage/AppStorageV2实现,适用于API19以前,API19以后建议使用方案一。
该方案与场景一中方案二实现思路基本一致,额外补充如下:
V2版本的父组件不能通过AppStorage中的@StorageLink自动同步刷新,只能通过AppStorage.get手动获取,建议通过AppStorageV2实现。
完整示例代码如下:
import { AppStorageV2 } from '@kit.ArkUI';
@ObservedV2
class V2ToV1ExampleTwoV2 {
@Trace text: string = '1';
constructor(text: string) {
this.text = text;
}
}
@Entry
@ComponentV2
struct V2ToV1Two {
@Local exampleAppStorageV2: V2ToV1ExampleTwoV2 =
AppStorageV2.connect<V2ToV1ExampleTwoV2>(V2ToV1ExampleTwoV2, () => new V2ToV1ExampleTwoV2('1'))!;
build() {
Column({ space: 10 }) {
Text(V2父组件,AppStorageV2:${this.exampleAppStorageV2.text});
Button('V2 中修改')
.onClick(() => {
this.exampleAppStorageV2.text += '1';
});
Column() {
}
.height(50);
V2ToV1TwoChild();
}.width('100%');
}
}
@Component
struct V2ToV1TwoChild {
exampleAppStorageV2: V2ToV1ExampleTwoV2 =
AppStorageV2.connect<V2ToV1ExampleTwoV2>(V2ToV1ExampleTwoV2, () => new V2ToV1ExampleTwoV2('1'))!; // 不可直接使用V1装饰器装饰
build() {
Column({ space: 10 }) {
Text(V1子组件,AppStorageV2:${this.exampleAppStorageV2.text});
Button('V1 中修改')
.onClick(() => {
this.exampleAppStorageV2.text += '1';
});
};
}
}
实现效果如下:
点击放大
方案三:传参方式,适用于API19以前,API19以后建议使用方案一。
该方案与场景一中方案三实现思路基本一致,额外补充如下:
该场景下V2组件作为父组件,V1组件作为子组件。@ObjectLink装饰器可以在V1子组件内使用,所以传递的参数既可以是@Observed装饰器装饰的类,也可以是@ObservedV2/@Trace装饰器装饰的类(@ObservedV2/@Trace装饰器的场景参考下文“方式三,对象参数传递”的场景)。
V2组件作为子组件时,只能通过@Param装饰器接收参数,但是当V1组件作为子组件时,可以通过@Prop、@ObjectLink、@Link三种装饰器接收参数。但是根据知识背景中的混用校验规则,@Link只能被V1状态变量初始化,详情见@Link变量的传递/访问规则说明,所以使用@Prop、@ObjectLink接收V2父组件传递来的参数。
在实现“方式三,对象参数传递”的场景时,由于@ObservedV2/@Trace装饰的类可以直接在V2组件内声明,所以将@ObservedV2/@Trace装饰的类实例化后作为属性传递即可。
完整示例代码如下:
@Observed
class V2ToV1ExampleThreeV1 {
text: string = '1';
constructor(text: string) {
this.text = text;
}
}
class V2ToV1ExampleThreeFather {
example: V2ToV1ExampleThreeV1 = new V2ToV1ExampleThreeV1('1');
}
@ObservedV2
class V2ToV1ExampleThreeV2 {
@Trace text: string = '1';
constructor(text: string) {
this.text = text;
}
}
interface V2ToV1ExampleThreeFatherV2Face {
example: V2ToV1ExampleThreeV2;
}
interface V2ToV1ExampleThreeFace {
text: string;
}
@Entry
@ComponentV2
struct V2ToV1Three {
// 方式一,不使用V2装饰器在V2组件内初始化V1装饰器@Observed装饰的类
exampleOne: V2ToV1ExampleThreeV1 = new V2ToV1ExampleThreeV1('1');
// 方式二,将V1装饰器@Observed装饰的类嵌套进不带任何装饰器装饰的类里,再进行初始化
@Local exampleTwo: V2ToV1ExampleThreeFather = new V2ToV1ExampleThreeFather();
// 方式三,传递简单类型
@Local text: string = '1';
// 方式三,@ObservedV2装饰的类的实例化后传递
@Local exampleFour: V2ToV1ExampleThreeV2 = new V2ToV1ExampleThreeV2('1');
build() {
Column({ space: 10 }) {
Text(V2父组件,方式一,参数传递:${this.exampleOne.text}); // 不刷新
Text(V2父组件,方式二,参数传递:${this.exampleTwo.example.text}); // 不刷新
Text(V2父组件,方式三,简单类型参数传递:${this.text}); // 刷新
Text(V2父组件,方式三,对象参数传递:${this.exampleFour.text}); // 刷新
Button('V2 中修改')
.onClick(() => {
// 方式一,数据在V2父组件中修改方式
this.exampleOne.text += '1';
// 方式二,数据在V2父组件中修改方式
this.exampleTwo.example.text += '1';
// 方式三,传递简单类型在V2父组件中修改方式
this.text += '1';
// 方式三,传递@ObservedV2装饰的对象在V2父组件中修改方式
this.exampleFour.text += '1';
});
Column() {
}
.height(20);
V2ToV1ThreeChild({
// 方式一,可直接传递
exampleOne: this.exampleOne,
// 方式二,传递的是封装后的属性
exampleTwo: this.exampleTwo.example,
// 方式三,将字符串作为对象的属性传递
exampleThree: {
text: this.text
},
changeText: () => {
this.text += '1';
},
// 方式三,将声明的@ObservedV2装饰的对象作为属性传递
exampleFour: {
example: this.exampleFour
}
});
}.width('100%');
}
}
@Component
struct V2ToV1ThreeChild {
// 方式一接收的数据
@Prop exampleOne: V2ToV1ExampleThreeV1;
// 方式二接受的数据
@ObjectLink exampleTwo: V2ToV1ExampleThreeV1;
// 方式三(传递简单类型)接收的数据
@Prop exampleThree: V2ToV1ExampleThreeFace;
// 父组件传递的是简单类型变量时必备,不然无法同步修改父组件字符串内容
changeText: () => void = () => {
};
// 方式三(传递对象)接收的数据
@ObjectLink exampleFour: V2ToV1ExampleThreeFatherV2Face;
build() {
Column({ space: 10 }) {
Text(V1子组件,方式一,参数传递:${this.exampleOne.text});
Text(V1子组件,方式二,参数传递:${this.exampleTwo.text});
Text(V1子组件,方式三,简单类型参数传递:${this.exampleThree.text});
Text(V1子组件,方式三,对象参数传递:${this.exampleFour.example.text});
Button('V1 中修改')
.onClick(() => {
// 方式一,数据在V1子组件中修改方式
this.exampleOne.text += '1';
// 方式二,数据在V1子组件中修改方式
this.exampleTwo.text += '1';
// 方式三,传递简单类型在V1子组件中修改方式
this.changeText();
// 方式三,传递对象在V1子组件中修改方式
this.exampleFour.example.text += '1';
});
};
}
}
实现效果如下:
点击放大
注意
@Observed/@ObjectLink可以实现父组件修改深层属性后,刷新子组件对应属性绑定的UI的功能,但是当子组件内修改深层属性,父组件并不会刷新对应属性绑定的UI。所以除了通过方式三以外的方式一、方式二不会刷新父组件绑定的对应属性的UI。
常见FAQ
Q:使用Navigation导航的应用在V1版本中用的是@Provide/@Consume装饰器传递的NavPathStack路由栈。在V1迁移V2过程中,Navigation主页被修改为V2版本,子页依旧是保持的V1版本。此时应该怎样传递NavPathStack路由栈给子页面?
A:由于@ComponentV2内不能使用V1版本的@Provide/@Consume装饰器,@Component内不能使用V2版本的@Provider/@Consumer装饰器,所以当父子组件分别属于V1、V2版本时,不能使用@Provider/@Consumer、@Provide/@Consume去实现组件见页面的共享与数据传递。可参考解决方案如下:
使用AppStorage存储或者获取数据:在Navigation主页面通过AppStorage.setOrCreate进行全局存储,在V1版本的NavDestination子页面内直接通过@StorageLink进行全局路由栈获取。
使用AppStorageV2存储或者获取数据:分别在父组件与子组件通过pathStack: NavPathStack = AppStorageV2.connect(NavPathStack, () => new NavPathStack())!;创建或获取全局路由栈。
如果页面中使用了NavDestination组件,可以通过onReady事件获取路由栈:.onReady((context: NavDestinationContext) => {this.pathInfos = context.pathStack}),从而避免状态管理版本冲突的问题。
通过自定义组件查询接口获取,也可以避免状态管理传递冲突的问题,参考queryNavigationInfo。
Q:在V1迁移V2的过程中,存在部分三方库是V1版本实现,还没适配V2版本,应该如何将V2版本的数据传递给V1版本三方库?
A:建议参考场景二中方案一,方案三实现。该场景下,方案二AppStorageV2.connect没办法写进三方库内。
总结
在API19之后,优先推荐使用官方提供的UIUtils.enableV2Compatibility方法实现V1、V2版本之间父子组件的数据传递与共享。
https://coub.com/view/4b707t
https://coub.com/view/4b707r
https://coub.com/view/4b707o
https://coub.com/view/4b707n
https://coub.com/view/4b707h
https://coub.com/view/4b707d
https://coub.com/view/4b7077
https://coub.com/view/4b7074
https://coub.com/view/4b706z
https://coub.com/view/4b706u
https://coub.com/view/4b706o
https://coub.com/view/4b706c
https://coub.com/view/4b7063
https://coub.com/view/4b7060
https://coub.com/view/4b705v
https://coub.com/view/4b705n
https://coub.com/view/4b705k
https://coub.com/view/4b701z
https://coub.com/view/4b6zjc
https://coub.com/view/4b6zja
https://coub.com/view/4b6zj9
https://coub.com/view/4b6zj6
https://coub.com/view/4b6zj4
https://coub.com/view/4b6zj3
https://coub.com/view/4b6zj2
https://coub.com/view/4b6zj1
https://coub.com/view/4b6ziz
https://coub.com/view/4b6zix
https://coub.com/view/4b6ziv
https://coub.com/view/4b6ziu
https://coub.com/view/4b6zit
https://coub.com/view/4b6zis
https://coub.com/view/4b6zio
https://coub.com/view/4b6zin
https://coub.com/view/4b6zim
https://coub.com/view/4b6zik
推荐一款 护航跑刀电竞下单系统,仓库开源 前后端
仓库地址
https://gitee.com/zhangshangshidai/dailianhuhang
电竞护航下单系统 | UniApp + ThinkPHP6
2026年最火的游戏模式,三角洲等游戏的护航陪玩模式,面向游戏工作室、代练工作室、电竞护航工作室打造的订单管理交易系统,一套完整前后端开源方案,快速搭建电竞护航、游戏代练线上下单平台。
🛠️ 技术栈
前端:UniApp,支持编译 H5、微信小程序、App 多端
后端:ThinkPHP6 RESTful API
数据库:MySQL,支持 Redis 缓存拓展
✨ 核心功能
后台管理端
游戏分类管理,自定义游戏列表
护航商品发布,支持多规格价格、多属性配置、多图片上传
订单统一管理,接单操作,录入打手信息,订单完结处理
用户管理、资金配置、支付渠道配置、退款审核
用户客户端
用户注册登录,个人中心
浏览护航商品,在线下单
支付方式:微信支付、账户余额支付
完整订单流程:待接单、进行中、已完成、退款申请
订单详情查询,提交退款申请
余额明细、消费记录查看
🎯 项目优势
专为电竞护航、游戏代练工作室业务场景定制,贴合行业流程
UniApp 多端适配,小程序 / H5/App 任选上线
商品支持多规格多价位,满足不同段位、时长护航套餐需求
订单闭环完整:下单→支付→后台接单→登记打手→完成 / 退款
双支付模式,余额体系便于工作室老客户复购结算
代码分层清晰,易于二次开发、自定义功能迭代
📌 适用主体
电竞护航工作室、游戏代练工作室、游戏陪玩工作室、线上游戏服务交易团队
🚀 部署简述
后端部署 PHP 环境,导入数据库,配置数据库与支付参数
HBuilderX 打开 UniApp 前端项目,修改后端接口地址
编译打包对应端(小程序 / H5/App)即可投入使用
仓库地址
https://gitee.com/zhangshangshidai/dailianhuhang
电竞护航下单系统 | UniApp + ThinkPHP6
2026年最火的游戏模式,三角洲等游戏的护航陪玩模式,面向游戏工作室、代练工作室、电竞护航工作室打造的订单管理交易系统,一套完整前后端开源方案,快速搭建电竞护航、游戏代练线上下单平台。
🛠️ 技术栈
前端:UniApp,支持编译 H5、微信小程序、App 多端
后端:ThinkPHP6 RESTful API
数据库:MySQL,支持 Redis 缓存拓展
✨ 核心功能
后台管理端
游戏分类管理,自定义游戏列表
护航商品发布,支持多规格价格、多属性配置、多图片上传
订单统一管理,接单操作,录入打手信息,订单完结处理
用户管理、资金配置、支付渠道配置、退款审核
用户客户端
用户注册登录,个人中心
浏览护航商品,在线下单
支付方式:微信支付、账户余额支付
完整订单流程:待接单、进行中、已完成、退款申请
订单详情查询,提交退款申请
余额明细、消费记录查看
🎯 项目优势
专为电竞护航、游戏代练工作室业务场景定制,贴合行业流程
UniApp 多端适配,小程序 / H5/App 任选上线
商品支持多规格多价位,满足不同段位、时长护航套餐需求
订单闭环完整:下单→支付→后台接单→登记打手→完成 / 退款
双支付模式,余额体系便于工作室老客户复购结算
代码分层清晰,易于二次开发、自定义功能迭代
📌 适用主体
电竞护航工作室、游戏代练工作室、游戏陪玩工作室、线上游戏服务交易团队
🚀 部署简述
后端部署 PHP 环境,导入数据库,配置数据库与支付参数
HBuilderX 打开 UniApp 前端项目,修改后端接口地址
编译打包对应端(小程序 / H5/App)即可投入使用
如何实现页面上滑tabBar和顶部标题的悬停以及属性动画效果
问题现象
参照Scroll的示例3,实现了tabBar在页面顶部的悬停效果。
如果页面顶部还有一个标题栏(即下图中“首页”),现在要实现tab内容向上滚动时tabBar悬停到标题栏下方(即下图中“同城”,“推荐”,“活动”,“玩机”这一行),且可以实现标题栏在滚动过程中样式变化(如下图背景变化),该如何实现?
点击放大点击放大
背景知识
Stack:堆叠容器,子组件按照顺序依次入栈,后一个子组件覆盖前一个子组件。
Scroll:可滚动的容器组件,当子组件的布局尺寸超过父组件的尺寸时,内容可以滚动。
nestedScroll:设置前后两个方向的嵌套滚动模式,实现与父组件的滚动联动。
onDidScroll:滚动事件回调,Scroll滚动时触发。
解决方案
使用Stack层叠布局,将标题栏悬浮展示在页面顶部。
考虑页面滚动以及tabContent里面的list滚动,就要考虑滚动嵌套问题,目前场景需要选择:
向上滚动时:父组件先滚动,父组件滚动到边缘以后自身滚动;
向下滚动时:自身先滚动,自身滚动到边缘以后父组件滚动。
示例代码如下:
.nestedScroll({
scrollForward: NestedScrollMode.PARENT_FIRST,
scrollBackward: NestedScrollMode.SELF_FIRST
});
父组件滚动过程中,根据滚动偏移量线性修改标题栏样式(如字体大小、透明度、背景等),onDidScroll可以返回当前帧滚动的偏移量和当前滚动状态。
示例代码如下:
@Entry
@Component
struct StickyNestedScroll {
@State arr: number[] = [];
@State opacityNum: number = 0;
@State curYOffset: number = 0;
@State currentIndex: number = 0;
aboutToAppear() {
for (let i = 0; i < 30; i++) {
this.arr.push(i);
}
}
@Styles
listCard() {
.backgroundColor('#FFF')
.height(64)
.width('calc(100% - 32vp)')
.borderRadius(20)
.margin({
left: 16,
right: 16,
});
}
@Builder
tabBuilder(title: string, targetIndex: number) {
Column() {
Text(title)
.fontColor(this.currentIndex === targetIndex ? '#FFF' : '#000')
.fontSize(14)
.fontWeight(this.currentIndex === targetIndex ? 500 : 400);
}
.height(36)
.padding({
left: 16,
right: 16,
})
.margin({ left: 8 })
.borderRadius(20)
.backgroundColor(this.currentIndex === targetIndex ? '#0A59F7' : 'rgba(0, 0, 0, 0.05)')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center);
}
build() {
Stack() {
Scroll() {
Column() {
Image($r('app.media.scrollTopbg')) // 图片资源需自行替换
.width('100%')
.height(300);
Tabs({ barPosition: BarPosition.Start }) {
ForEach(this.arr.slice(0, 6),
(item: number, index: number) => {
TabContent() {
List({ space: 16 }) {
ForEach(this.arr, (item1: number) => {
ListItem() {
Text('item' + item1)
.fontSize(16).fontWeight(400);
}.listCard();
}, (item1: string) => item1);
}.width('100%')
.edgeEffect(EdgeEffect.None)
.nestedScroll({
scrollForward: NestedScrollMode.PARENT_FIRST,
scrollBackward: NestedScrollMode.SELF_FIRST
});
}.tabBar(this.tabBuilder(`标签${item + 1}`, index));
}, (item: number, index: number) => JSON.stringify(item) + index);
}
.onChange((index) => {
this.currentIndex = index;
})
.barMode(BarMode.Scrollable)
.barHeight(72)
.vertical(false)
.width('100%')
.height('calc(100% - 80vp)');
}.width('100%');
}
.friction(0.6)
.scrollBar(BarState.Off)
.width('100%')
.height('100%')
.onDidScroll((xOffset: number, yOffset: number, scrollState: ScrollState): void => {
// 累计计算当前父组件滚动在Y轴方向的偏移量
this.curYOffset += yOffset;
// 根据父组件一共可以滚动的距离计算当前每帧的当前透明度
let opacity = this.curYOffset / 220;
if (opacity >= 1) {
opacity = 1;
}
if (opacity <= 0) {
opacity = 0;
}
this.opacityNum = opacity;
console.info(`xOffset: ${xOffset},scrollState:${scrollState}`);
});
// 悬浮标题栏
Text('工作台')
.fontSize(24)
.fontColor('#000')
.fontWeight(FontWeight.Bold)
.backgroundColor(`rgba(255,255,255,${this.opacityNum})`)
.position({ x: 0, y: 0 })
.width('100%')
.height(80)
.padding({ left: 16, top: 44 });
}.width('100%')
.height('100%').background('#F1F3F5');
}
}
效果如图:
点击放大
总结
悬浮类布局首先考虑Stack层叠布局。
嵌套滚动,考虑父子组件之间的先后滚动模式,选择合适的滚动模式。
滚动过程中,获取当前滚动每帧偏移量和滚动状态,做合适的UI更新。
https://pastebin.com/H9s5Prqc
https://pastebin.com/B3rdpE0P
https://pastebin.com/1DnHtpyd
https://pastebin.com/TEdBHtNb
https://pastebin.com/LJ0cQ7Uu
https://pastebin.com/bEc1mLCD
https://pastebin.com/kgSG3Gqx
https://pastebin.com/562Mtrb0
https://pastebin.com/TcJ1ucZM
https://pastebin.com/NdYhTKwU
https://pastebin.com/0kg2myHE
https://pastebin.com/tuXkKyRR
https://pastebin.com/JNaUA51y
https://pastebin.com/RqerbF2p
https://pastebin.com/jzeTmGu6
https://pastebin.com/bG1T2kG0
https://pastebin.com/2waPB0AK
https://pastebin.com/miLDPTFG
https://pastebin.com/2GVXUYr6
https://pastebin.com/RDfika4N
https://pastebin.com/yVTUxb9T
https://pastebin.com/8fpFzpMF
https://pastebin.com/dxrwgxZb
https://pastebin.com/WW5LdheP
https://pastebin.com/j9dwuCiX
https://pastebin.com/4pjqADUq
https://pastebin.com/RMeYiqCG
https://pastebin.com/jcEZ3mCw
https://pastebin.com/u0UKBHMc
https://pastebin.com/6AtALgcG
https://pastebin.com/yZZZgpRJ
https://pastebin.com/LbQCHdWp
https://pastebin.com/8uaaUxm3
https://pastebin.com/smKGwEkJ
https://pastebin.com/XZS8Lgc9
https://pastebin.com/PXPcxxu5
https://pastebin.com/AzHkpzSh
https://pastebin.com/kdDFUmsj
https://pastebin.com/ejETYeux
https://pastebin.com/s4Tj7hqX
https://pastebin.com/n8vn16hR
https://pastebin.com/cUBURDS5
https://pastebin.com/iHuTYWub
https://pastebin.com/it84K7XW
https://pastebin.com/dHhXdDc4
https://pastebin.com/btsEnW55
https://pastebin.com/VhQvwq6f
https://pastebin.com/prMTmsc5
https://pastebin.com/giVp1BpF
https://pastebin.com/fQyYpmGY
https://pastebin.com/gAg3F6UY
https://pastebin.com/2QWLCNvx
https://pastebin.com/2gxy4TKg
https://pastebin.com/xKYNRWMk
https://pastebin.com/1HxCD5DS
https://pastebin.com/GiAXtWj1
https://pastebin.com/m8afMq62
https://pastebin.com/55Xb4vqW
https://pastebin.com/zJcq0WY7
https://pastebin.com/WmVwfQrY
https://pastebin.com/91bnWbQF
https://pastebin.com/gvKhZ9Tc
https://pastebin.com/Nt21BqQ7
https://pastebin.com/wM2aTQ0w
https://pastebin.com/Vc7vvzKJ
https://pastebin.com/yaq33eZQ
https://pastebin.com/qZ5F9NYb
https://pastebin.com/i3E4FgCp
https://pastebin.com/AkTA5RZZ
https://pastebin.com/ELEG1B0m
https://pastebin.com/5JWdPFhR
https://pastebin.com/R0YTHUS4
https://pastebin.com/x9nRf1j0
https://pastebin.com/Aih0qsy2
https://pastebin.com/CpwvWE4e
https://pastebin.com/rr9rRU2E
https://pastebin.com/6Ye4Gwq7
https://pastebin.com/DAw6tKSy
https://pastebin.com/6gFkNdxP
https://pastebin.com/zMtnD7tM
https://pastebin.com/95F1ruf8
https://pastebin.com/ZXeMfgMs
https://pastebin.com/s8Xu4WDd
https://pastebin.com/cTfEk1wu
https://pastebin.com/Mjm4d4Rz
https://pastebin.com/gRAQUhkK
https://pastebin.com/YpNWSg6u
https://pastebin.com/51Edu6ba
https://pastebin.com/XkAuM8JZ
https://pastebin.com/vcnnDhb9
https://pastebin.com/hjhUzWgG
https://pastebin.com/Za2eji2y
https://pastebin.com/6HcM5ez2
https://pastebin.com/iKpg8iex
https://pastebin.com/9zDKuETK
https://pastebin.com/M4swhPLu
https://pastebin.com/BFs6X9UX
https://pastebin.com/GWjxjEgb
https://pastebin.com/E1LbLCgp
https://pastebin.com/Ze95QMAi
https://pastebin.com/ZY8zYNWn
https://pastebin.com/fTLHPLZZ
https://pastebin.com/6fDk9tYi
https://pastebin.com/GfuDHVfH
https://pastebin.com/KUq4BLce
https://pastebin.com/qY5k2ZxX
https://pastebin.com/8yXshjhD
https://pastebin.com/3BmddLGG
https://pastebin.com/6hgiPSQy
https://pastebin.com/pwCxCvBx
https://pastebin.com/rdgB20Hq
https://pastebin.com/fR1AXxN3
https://pastebin.com/XAyJJSh4
https://pastebin.com/Udz89NF9
https://pastebin.com/tRFNRTfq
https://pastebin.com/LYnbJkDX
https://pastebin.com/UrndZZ4r
https://pastebin.com/UJ0cJu7W
https://pastebin.com/VC9ftumY
https://pastebin.com/1mD57fxS
https://pastebin.com/4yCvSzPt
https://pastebin.com/Tds1KK8q
https://pastebin.com/cuTV0ANH
https://pastebin.com/tfvAj5zG
https://pastebin.com/YmTJJ9P4
https://pastebin.com/qr720c8a
https://pastebin.com/Qzx9z0jT
https://pastebin.com/phurPJTs
https://pastebin.com/gHHTkHD3
https://pastebin.com/ZwnPCDTj
https://pastebin.com/0DSjtHAt
https://pastebin.com/TftyJMxx
https://pastebin.com/vBBJvgLm
https://pastebin.com/NQYakApj
https://pastebin.com/meCbWSmb
https://pastebin.com/1VP7BDiy
https://pastebin.com/9dwnBKrH
https://pastebin.com/CfNxq9BD
https://pastebin.com/7SdTHhbB
https://pastebin.com/wjGatMb0
https://pastebin.com/Gv2kQv0K
https://pastebin.com/kqY5ZC2U
https://pastebin.com/NVQSYDC2
https://pastebin.com/p5cmmLTs
https://pastebin.com/ksUjWjEf
https://pastebin.com/iGqdf7JS
https://pastebin.com/1jPPW8SY
https://pastebin.com/zaiTAPGu
https://pastebin.com/ZyCEaVhf
https://pastebin.com/Z8nhRzGY
https://pastebin.com/4ANEqn0d
https://pastebin.com/B6aK9n6G
https://pastebin.com/0Tt4rGw1
https://pastebin.com/jV1WDDj1
https://pastebin.com/epsfQ9xR
https://pastebin.com/TDsuwVQq
https://pastebin.com/1sCfUZ1r
https://pastebin.com/rPZVVY9W
https://pastebin.com/YMAeatYs
https://pastebin.com/USZwiZLz
https://pastebin.com/0D4g5hpe
https://pastebin.com/aTgxSFAv
https://pastebin.com/d9yLduCs
https://pastebin.com/t2jGSt52
https://pastebin.com/ZCjZZ5cd
https://pastebin.com/fYBzqBQc
https://pastebin.com/rPSifbkZ
https://pastebin.com/r5hsmStB
https://pastebin.com/GBQJqUpA
https://pastebin.com/wi5TgU60
https://pastebin.com/17bmtrLm
https://pastebin.com/ymjx0ej6
https://pastebin.com/tnhPx5tx
https://pastebin.com/pKythJNa
https://pastebin.com/7rkBm8RR
https://pastebin.com/nKrgz0hx
https://pastebin.com/Ls4U30up
https://pastebin.com/GLrgZDKM
https://pastebin.com/QLenyQyb
https://pastebin.com/6kf7ctaD
https://pastebin.com/493xDX2E
https://pastebin.com/NNLBP1BA
https://pastebin.com/fQsBphT0
https://pastebin.com/iFUr5gqq
https://pastebin.com/YkZtGRGV
https://pastebin.com/CUgpDscE
https://pastebin.com/4BSRJRJ2
https://pastebin.com/rgaPPPXy
https://pastebin.com/e0MbXcLH
https://pastebin.com/0y661SPV
https://pastebin.com/WnhafHAL
https://pastebin.com/vdcuA6Wn
https://pastebin.com/0wP7iM13
https://pastebin.com/kSsbb7uN
https://pastebin.com/CKuHJUp0
https://pastebin.com/VFHuYY0w
https://pastebin.com/e57GMSyT
https://pastebin.com/JCJqt21y
https://pastebin.com/v03W6Wua
https://pastebin.com/Qh5cvmxD
https://pastebin.com/1n1rmrga
https://pastebin.com/EqpNrUd9
https://pastebin.com/hNzVc4VA
https://pastebin.com/wyd61PAX
https://pastebin.com/KUqAc0dA
https://pastebin.com/dAwvfQ3n
https://pastebin.com/tfhzjx0X
https://pastebin.com/qcry1nbc
https://pastebin.com/Xx1xKrr5
https://pastebin.com/z4RRXjbZ
https://pastebin.com/HFUs4bbZ
https://pastebin.com/7hFpzwBb
https://pastebin.com/kkxJEXkH
https://pastebin.com/8N244GbV
https://pastebin.com/6QgG0hC0
https://pastebin.com/SPfWYRk3
https://pastebin.com/CQQ6jn3J
https://pastebin.com/KHGYtVZu
https://pastebin.com/ibnJTTYm
问题现象
参照Scroll的示例3,实现了tabBar在页面顶部的悬停效果。
如果页面顶部还有一个标题栏(即下图中“首页”),现在要实现tab内容向上滚动时tabBar悬停到标题栏下方(即下图中“同城”,“推荐”,“活动”,“玩机”这一行),且可以实现标题栏在滚动过程中样式变化(如下图背景变化),该如何实现?
点击放大点击放大
背景知识
Stack:堆叠容器,子组件按照顺序依次入栈,后一个子组件覆盖前一个子组件。
Scroll:可滚动的容器组件,当子组件的布局尺寸超过父组件的尺寸时,内容可以滚动。
nestedScroll:设置前后两个方向的嵌套滚动模式,实现与父组件的滚动联动。
onDidScroll:滚动事件回调,Scroll滚动时触发。
解决方案
使用Stack层叠布局,将标题栏悬浮展示在页面顶部。
考虑页面滚动以及tabContent里面的list滚动,就要考虑滚动嵌套问题,目前场景需要选择:
向上滚动时:父组件先滚动,父组件滚动到边缘以后自身滚动;
向下滚动时:自身先滚动,自身滚动到边缘以后父组件滚动。
示例代码如下:
.nestedScroll({
scrollForward: NestedScrollMode.PARENT_FIRST,
scrollBackward: NestedScrollMode.SELF_FIRST
});
父组件滚动过程中,根据滚动偏移量线性修改标题栏样式(如字体大小、透明度、背景等),onDidScroll可以返回当前帧滚动的偏移量和当前滚动状态。
示例代码如下:
@Entry
@Component
struct StickyNestedScroll {
@State arr: number[] = [];
@State opacityNum: number = 0;
@State curYOffset: number = 0;
@State currentIndex: number = 0;
aboutToAppear() {
for (let i = 0; i < 30; i++) {
this.arr.push(i);
}
}
@Styles
listCard() {
.backgroundColor('#FFF')
.height(64)
.width('calc(100% - 32vp)')
.borderRadius(20)
.margin({
left: 16,
right: 16,
});
}
@Builder
tabBuilder(title: string, targetIndex: number) {
Column() {
Text(title)
.fontColor(this.currentIndex === targetIndex ? '#FFF' : '#000')
.fontSize(14)
.fontWeight(this.currentIndex === targetIndex ? 500 : 400);
}
.height(36)
.padding({
left: 16,
right: 16,
})
.margin({ left: 8 })
.borderRadius(20)
.backgroundColor(this.currentIndex === targetIndex ? '#0A59F7' : 'rgba(0, 0, 0, 0.05)')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center);
}
build() {
Stack() {
Scroll() {
Column() {
Image($r('app.media.scrollTopbg')) // 图片资源需自行替换
.width('100%')
.height(300);
Tabs({ barPosition: BarPosition.Start }) {
ForEach(this.arr.slice(0, 6),
(item: number, index: number) => {
TabContent() {
List({ space: 16 }) {
ForEach(this.arr, (item1: number) => {
ListItem() {
Text('item' + item1)
.fontSize(16).fontWeight(400);
}.listCard();
}, (item1: string) => item1);
}.width('100%')
.edgeEffect(EdgeEffect.None)
.nestedScroll({
scrollForward: NestedScrollMode.PARENT_FIRST,
scrollBackward: NestedScrollMode.SELF_FIRST
});
}.tabBar(this.tabBuilder(`标签${item + 1}`, index));
}, (item: number, index: number) => JSON.stringify(item) + index);
}
.onChange((index) => {
this.currentIndex = index;
})
.barMode(BarMode.Scrollable)
.barHeight(72)
.vertical(false)
.width('100%')
.height('calc(100% - 80vp)');
}.width('100%');
}
.friction(0.6)
.scrollBar(BarState.Off)
.width('100%')
.height('100%')
.onDidScroll((xOffset: number, yOffset: number, scrollState: ScrollState): void => {
// 累计计算当前父组件滚动在Y轴方向的偏移量
this.curYOffset += yOffset;
// 根据父组件一共可以滚动的距离计算当前每帧的当前透明度
let opacity = this.curYOffset / 220;
if (opacity >= 1) {
opacity = 1;
}
if (opacity <= 0) {
opacity = 0;
}
this.opacityNum = opacity;
console.info(`xOffset: ${xOffset},scrollState:${scrollState}`);
});
// 悬浮标题栏
Text('工作台')
.fontSize(24)
.fontColor('#000')
.fontWeight(FontWeight.Bold)
.backgroundColor(`rgba(255,255,255,${this.opacityNum})`)
.position({ x: 0, y: 0 })
.width('100%')
.height(80)
.padding({ left: 16, top: 44 });
}.width('100%')
.height('100%').background('#F1F3F5');
}
}
效果如图:
点击放大
总结
悬浮类布局首先考虑Stack层叠布局。
嵌套滚动,考虑父子组件之间的先后滚动模式,选择合适的滚动模式。
滚动过程中,获取当前滚动每帧偏移量和滚动状态,做合适的UI更新。
https://pastebin.com/H9s5Prqc
https://pastebin.com/B3rdpE0P
https://pastebin.com/1DnHtpyd
https://pastebin.com/TEdBHtNb
https://pastebin.com/LJ0cQ7Uu
https://pastebin.com/bEc1mLCD
https://pastebin.com/kgSG3Gqx
https://pastebin.com/562Mtrb0
https://pastebin.com/TcJ1ucZM
https://pastebin.com/NdYhTKwU
https://pastebin.com/0kg2myHE
https://pastebin.com/tuXkKyRR
https://pastebin.com/JNaUA51y
https://pastebin.com/RqerbF2p
https://pastebin.com/jzeTmGu6
https://pastebin.com/bG1T2kG0
https://pastebin.com/2waPB0AK
https://pastebin.com/miLDPTFG
https://pastebin.com/2GVXUYr6
https://pastebin.com/RDfika4N
https://pastebin.com/yVTUxb9T
https://pastebin.com/8fpFzpMF
https://pastebin.com/dxrwgxZb
https://pastebin.com/WW5LdheP
https://pastebin.com/j9dwuCiX
https://pastebin.com/4pjqADUq
https://pastebin.com/RMeYiqCG
https://pastebin.com/jcEZ3mCw
https://pastebin.com/u0UKBHMc
https://pastebin.com/6AtALgcG
https://pastebin.com/yZZZgpRJ
https://pastebin.com/LbQCHdWp
https://pastebin.com/8uaaUxm3
https://pastebin.com/smKGwEkJ
https://pastebin.com/XZS8Lgc9
https://pastebin.com/PXPcxxu5
https://pastebin.com/AzHkpzSh
https://pastebin.com/kdDFUmsj
https://pastebin.com/ejETYeux
https://pastebin.com/s4Tj7hqX
https://pastebin.com/n8vn16hR
https://pastebin.com/cUBURDS5
https://pastebin.com/iHuTYWub
https://pastebin.com/it84K7XW
https://pastebin.com/dHhXdDc4
https://pastebin.com/btsEnW55
https://pastebin.com/VhQvwq6f
https://pastebin.com/prMTmsc5
https://pastebin.com/giVp1BpF
https://pastebin.com/fQyYpmGY
https://pastebin.com/gAg3F6UY
https://pastebin.com/2QWLCNvx
https://pastebin.com/2gxy4TKg
https://pastebin.com/xKYNRWMk
https://pastebin.com/1HxCD5DS
https://pastebin.com/GiAXtWj1
https://pastebin.com/m8afMq62
https://pastebin.com/55Xb4vqW
https://pastebin.com/zJcq0WY7
https://pastebin.com/WmVwfQrY
https://pastebin.com/91bnWbQF
https://pastebin.com/gvKhZ9Tc
https://pastebin.com/Nt21BqQ7
https://pastebin.com/wM2aTQ0w
https://pastebin.com/Vc7vvzKJ
https://pastebin.com/yaq33eZQ
https://pastebin.com/qZ5F9NYb
https://pastebin.com/i3E4FgCp
https://pastebin.com/AkTA5RZZ
https://pastebin.com/ELEG1B0m
https://pastebin.com/5JWdPFhR
https://pastebin.com/R0YTHUS4
https://pastebin.com/x9nRf1j0
https://pastebin.com/Aih0qsy2
https://pastebin.com/CpwvWE4e
https://pastebin.com/rr9rRU2E
https://pastebin.com/6Ye4Gwq7
https://pastebin.com/DAw6tKSy
https://pastebin.com/6gFkNdxP
https://pastebin.com/zMtnD7tM
https://pastebin.com/95F1ruf8
https://pastebin.com/ZXeMfgMs
https://pastebin.com/s8Xu4WDd
https://pastebin.com/cTfEk1wu
https://pastebin.com/Mjm4d4Rz
https://pastebin.com/gRAQUhkK
https://pastebin.com/YpNWSg6u
https://pastebin.com/51Edu6ba
https://pastebin.com/XkAuM8JZ
https://pastebin.com/vcnnDhb9
https://pastebin.com/hjhUzWgG
https://pastebin.com/Za2eji2y
https://pastebin.com/6HcM5ez2
https://pastebin.com/iKpg8iex
https://pastebin.com/9zDKuETK
https://pastebin.com/M4swhPLu
https://pastebin.com/BFs6X9UX
https://pastebin.com/GWjxjEgb
https://pastebin.com/E1LbLCgp
https://pastebin.com/Ze95QMAi
https://pastebin.com/ZY8zYNWn
https://pastebin.com/fTLHPLZZ
https://pastebin.com/6fDk9tYi
https://pastebin.com/GfuDHVfH
https://pastebin.com/KUq4BLce
https://pastebin.com/qY5k2ZxX
https://pastebin.com/8yXshjhD
https://pastebin.com/3BmddLGG
https://pastebin.com/6hgiPSQy
https://pastebin.com/pwCxCvBx
https://pastebin.com/rdgB20Hq
https://pastebin.com/fR1AXxN3
https://pastebin.com/XAyJJSh4
https://pastebin.com/Udz89NF9
https://pastebin.com/tRFNRTfq
https://pastebin.com/LYnbJkDX
https://pastebin.com/UrndZZ4r
https://pastebin.com/UJ0cJu7W
https://pastebin.com/VC9ftumY
https://pastebin.com/1mD57fxS
https://pastebin.com/4yCvSzPt
https://pastebin.com/Tds1KK8q
https://pastebin.com/cuTV0ANH
https://pastebin.com/tfvAj5zG
https://pastebin.com/YmTJJ9P4
https://pastebin.com/qr720c8a
https://pastebin.com/Qzx9z0jT
https://pastebin.com/phurPJTs
https://pastebin.com/gHHTkHD3
https://pastebin.com/ZwnPCDTj
https://pastebin.com/0DSjtHAt
https://pastebin.com/TftyJMxx
https://pastebin.com/vBBJvgLm
https://pastebin.com/NQYakApj
https://pastebin.com/meCbWSmb
https://pastebin.com/1VP7BDiy
https://pastebin.com/9dwnBKrH
https://pastebin.com/CfNxq9BD
https://pastebin.com/7SdTHhbB
https://pastebin.com/wjGatMb0
https://pastebin.com/Gv2kQv0K
https://pastebin.com/kqY5ZC2U
https://pastebin.com/NVQSYDC2
https://pastebin.com/p5cmmLTs
https://pastebin.com/ksUjWjEf
https://pastebin.com/iGqdf7JS
https://pastebin.com/1jPPW8SY
https://pastebin.com/zaiTAPGu
https://pastebin.com/ZyCEaVhf
https://pastebin.com/Z8nhRzGY
https://pastebin.com/4ANEqn0d
https://pastebin.com/B6aK9n6G
https://pastebin.com/0Tt4rGw1
https://pastebin.com/jV1WDDj1
https://pastebin.com/epsfQ9xR
https://pastebin.com/TDsuwVQq
https://pastebin.com/1sCfUZ1r
https://pastebin.com/rPZVVY9W
https://pastebin.com/YMAeatYs
https://pastebin.com/USZwiZLz
https://pastebin.com/0D4g5hpe
https://pastebin.com/aTgxSFAv
https://pastebin.com/d9yLduCs
https://pastebin.com/t2jGSt52
https://pastebin.com/ZCjZZ5cd
https://pastebin.com/fYBzqBQc
https://pastebin.com/rPSifbkZ
https://pastebin.com/r5hsmStB
https://pastebin.com/GBQJqUpA
https://pastebin.com/wi5TgU60
https://pastebin.com/17bmtrLm
https://pastebin.com/ymjx0ej6
https://pastebin.com/tnhPx5tx
https://pastebin.com/pKythJNa
https://pastebin.com/7rkBm8RR
https://pastebin.com/nKrgz0hx
https://pastebin.com/Ls4U30up
https://pastebin.com/GLrgZDKM
https://pastebin.com/QLenyQyb
https://pastebin.com/6kf7ctaD
https://pastebin.com/493xDX2E
https://pastebin.com/NNLBP1BA
https://pastebin.com/fQsBphT0
https://pastebin.com/iFUr5gqq
https://pastebin.com/YkZtGRGV
https://pastebin.com/CUgpDscE
https://pastebin.com/4BSRJRJ2
https://pastebin.com/rgaPPPXy
https://pastebin.com/e0MbXcLH
https://pastebin.com/0y661SPV
https://pastebin.com/WnhafHAL
https://pastebin.com/vdcuA6Wn
https://pastebin.com/0wP7iM13
https://pastebin.com/kSsbb7uN
https://pastebin.com/CKuHJUp0
https://pastebin.com/VFHuYY0w
https://pastebin.com/e57GMSyT
https://pastebin.com/JCJqt21y
https://pastebin.com/v03W6Wua
https://pastebin.com/Qh5cvmxD
https://pastebin.com/1n1rmrga
https://pastebin.com/EqpNrUd9
https://pastebin.com/hNzVc4VA
https://pastebin.com/wyd61PAX
https://pastebin.com/KUqAc0dA
https://pastebin.com/dAwvfQ3n
https://pastebin.com/tfhzjx0X
https://pastebin.com/qcry1nbc
https://pastebin.com/Xx1xKrr5
https://pastebin.com/z4RRXjbZ
https://pastebin.com/HFUs4bbZ
https://pastebin.com/7hFpzwBb
https://pastebin.com/kkxJEXkH
https://pastebin.com/8N244GbV
https://pastebin.com/6QgG0hC0
https://pastebin.com/SPfWYRk3
https://pastebin.com/CQQ6jn3J
https://pastebin.com/KHGYtVZu
https://pastebin.com/ibnJTTYm
如何实现Matrix2D图形在画布中心点放大并旋转角度
问题现象
如何在画布中心点实现Matrix2D图形指定倍数的放大和指定角度的旋转?
背景知识
Matrix2D组件的方法rotate,能够以旋转点为中心、对当前矩阵进行右乘旋转运算,调用公式为:rotate(degree: number, rx?: number, ry?: number),其中degree为旋转角度,rx和ry为旋转中心点相对[0,0]点的水平和垂直方向坐标,如果[0,0]点通过translate发生移动,则以新的点计算相对的rx和ry值。
translate方法能够对当前矩阵进行左乘平移运算,调用公式为:translate(tx?: number, ty?: number)。
scale方法能够对当前矩阵进行右乘缩放运算,调用公式为:scale(sx?: number, sy?: number),其中sx和sy为水平和垂直缩放比例系数。以[0,0]为基准进行缩放,如果[0,0]点通过translate发生移动,则以移动后的点为基准点进行缩放。
解决方案
使用Flex布局将Canvas组件居中显示,创建矩形。
使用rotate方法对矩阵进行旋转操作,旋转角度由angle决定,旋转中心为矩形的中心;使用scale方法对矩阵进行缩放操作,缩放倍数由scaleTimesX和scaleTimesY决定,以中心点为基准进行缩放。rotate和scale存在调用顺序,遵循就近原则,因此需要将scale方法的使用放在rotate上方。
使用translate方法对矩阵进行平移操作,将画布的原点移动到画布的中心,即可将图形移动至画布中心。将经过变换的矩阵应用到CanvasRenderingContext2D对象上。
用fillRect()方法在画布上绘制矩形。
完整示例参考如下:
@Entry
@Component
struct MatrixChange {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private matrix: Matrix2D = new Matrix2D();
x: number = 50; // 图形大小
y: number = 50; // 图形大小
canvasWidth: number = 200; // 画布大小
canvasHeight: number = 200; // 画布大小
scaleTimesX: number = 2; // 缩放设置
scaleTimesY: number = 2; // 缩放设置
angle: number = -30; // 旋转角度
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width(this.canvasWidth)
.height(this.canvasHeight)
.backgroundColor('#0D5AF5')
.onReady(() => {
this.matrix.scaleX = 1;
this.matrix.scaleY = 1;
this.matrix.scale(this.scaleTimesX, this.scaleTimesY);
this.matrix.rotate(this.angle Math.PI / 180, this.x / 2, this.y / 2);
this.matrix.translate(this.canvasWidth / 2, this.canvasHeight / 2);
this.matrix.translate(-this.x this.scaleTimesX / 2, -this.y * this.scaleTimesY / 2);
this.context.setTransform(this.matrix);
this.context.fillRect(0, 0, this.x, this.y);
});
}
.width('100%')
.height('100%');
}
}
总结
Matrix2D图形能够在画布中心点放大指定倍数并旋转指定角度,该功能适用于需要展示图形并对其进行各种变换的场景,例如数据可视化、图形编辑器等。
https://pastebin.com/jYcy8DG4
https://pastebin.com/Hp1sbSaS
https://pastebin.com/hTxV2yyS
https://pastebin.com/TQCjtTcP
https://pastebin.com/JpF1LSct
https://pastebin.com/Fr3XnQdE
https://pastebin.com/yTvhcbNw
https://pastebin.com/hRe1DgNt
https://pastebin.com/M3y1HL1H
https://pastebin.com/VraVGXVf
https://pastebin.com/griS9fnH
https://pastebin.com/pwrdFgiY
https://pastebin.com/Pbn36K7e
https://pastebin.com/7DMANuaz
https://pastebin.com/rHKJdsZT
https://pastebin.com/NLD2BSd3
https://pastebin.com/95Shz0dA
https://pastebin.com/zhphtiyk
https://pastebin.com/3HY6p8t3
https://pastebin.com/XQEtXnKJ
https://pastebin.com/56Zk2nAE
https://pastebin.com/FHzZvcGp
https://pastebin.com/jvCBLRx8
https://pastebin.com/UQ8bqVpS
https://pastebin.com/H5XxuvFD
https://pastebin.com/ZTRtEnKD
https://pastebin.com/DXXEFpJ7
https://pastebin.com/Xz7is4PA
https://pastebin.com/ujgDH7CQ
https://pastebin.com/QXvsH58y
https://pastebin.com/Syp4LL5s
https://pastebin.com/CLgzB5B2
https://pastebin.com/B1P1eZiT
https://pastebin.com/XsyVXiCg
https://pastebin.com/1XCeaqAU
https://pastebin.com/Jw13Rebn
https://pastebin.com/DyCcgNsv
https://pastebin.com/7LEMiQZ2
https://pastebin.com/dS3rfyQ6
https://pastebin.com/wLwm6rp7
https://pastebin.com/4WGjDaH1
https://pastebin.com/zb1zD5aE
https://pastebin.com/c1zNryeR
https://pastebin.com/4s5BeWXh
https://pastebin.com/Ce3nxNXr
https://pastebin.com/cmj5c080
https://pastebin.com/1H5LCdEY
https://pastebin.com/zZkVFh7Q
https://pastebin.com/BBrYWefF
https://pastebin.com/U4vvzbtw
https://pastebin.com/BWKQJ9Bf
https://pastebin.com/B5CXLSym
https://pastebin.com/PebrcV9M
https://pastebin.com/Ee30dGS4
https://pastebin.com/beXkZr16
https://pastebin.com/qfWN2Ryj
https://pastebin.com/c7mAxDum
https://pastebin.com/MpP9YNFU
https://pastebin.com/SQ8jWZqx
https://pastebin.com/9VALda7W
https://pastebin.com/xZ8P3Ks8
https://pastebin.com/niR9ymit
https://pastebin.com/Rv0T6rUx
https://pastebin.com/jAh0PWYa
https://pastebin.com/3wv5Agv8
https://pastebin.com/EtNNfJmj
https://pastebin.com/a9j6TNjC
https://pastebin.com/x6xxPkPX
https://pastebin.com/az8dYRbQ
https://pastebin.com/husRdHb4
https://pastebin.com/ZQw2Pbhx
https://pastebin.com/C59eWK5e
https://pastebin.com/kzcn3KvK
https://pastebin.com/mT8ehVrP
https://pastebin.com/uv3DmK2r
https://pastebin.com/9A90NJRS
https://pastebin.com/nxKRJ6DM
https://pastebin.com/em4D4Psa
https://pastebin.com/sq1LkcWj
https://pastebin.com/X9Qr3LsF
https://pastebin.com/0yhb1G5u
https://pastebin.com/RNBk3wcp
https://pastebin.com/n21GrF8N
https://pastebin.com/BVGGULWt
https://pastebin.com/2LVYSav1
https://pastebin.com/37m2vAg8
https://pastebin.com/YALGJ9Dj
https://pastebin.com/MPrNKc2X
https://pastebin.com/WcQR7d4P
https://pastebin.com/frpzGFbV
https://pastebin.com/MTZN74bH
https://pastebin.com/4XFYvRhd
https://pastebin.com/XEnbVYfF
https://pastebin.com/iGNu6WyC
https://pastebin.com/iC4qCnDP
https://pastebin.com/SubVHQiU
https://pastebin.com/GtmFQfJ6
https://pastebin.com/PqcdaaqX
https://pastebin.com/wbpVhAa4
https://pastebin.com/Gs8c9UJM
https://pastebin.com/rvBJLy48
https://pastebin.com/qJhsAkBV
https://pastebin.com/GsUxwvRp
https://pastebin.com/xhtemkVi
https://pastebin.com/VpcarPwJ
https://pastebin.com/M2MZ4XjZ
https://pastebin.com/1hsmtBAh
https://pastebin.com/FBKiMKLM
https://pastebin.com/TFcszpgY
https://pastebin.com/wZyc488a
https://pastebin.com/eyzX1hF0
https://pastebin.com/pn2C5r5y
https://pastebin.com/dyHRSz7V
https://pastebin.com/qspZ7UVQ
https://pastebin.com/hXZ59vW5
https://pastebin.com/EBymVseu
https://pastebin.com/Pi2qAyiG
https://pastebin.com/r53FkZrX
https://pastebin.com/pBxp5x6P
https://pastebin.com/kRmwv8xX
https://pastebin.com/YPBtC4bD
https://pastebin.com/zaazK0qN
https://pastebin.com/MH9s5BWr
https://pastebin.com/kUWEmtQ3
https://pastebin.com/EiVfHUPQ
https://pastebin.com/F1zDdap8
https://pastebin.com/x6ninbWm
https://pastebin.com/kp5xBGss
https://pastebin.com/X8rLUdJN
https://pastebin.com/V1Zmj7FJ
https://pastebin.com/UheVuGRp
https://pastebin.com/yKHmpBX3
https://pastebin.com/GQaa3tDW
https://pastebin.com/D00GfaUn
https://pastebin.com/2bTz1JVU
https://pastebin.com/hhdmx2bc
https://pastebin.com/KaXVaXRZ
https://pastebin.com/R0R3JCNA
https://pastebin.com/zQGT96rX
https://pastebin.com/cbqQbPyf
https://pastebin.com/6PJN3M7N
https://pastebin.com/k1yeEBr9
https://pastebin.com/GAVHCfGW
https://pastebin.com/V9BDRArR
https://pastebin.com/Ms7giaW9
https://pastebin.com/ddfs4xn7
https://pastebin.com/bhtqrAfp
https://pastebin.com/hCwrGzXp
https://pastebin.com/Cf6NEq1t
https://pastebin.com/i2YZAQTR
https://pastebin.com/PBVaCkjV
https://pastebin.com/CZh9JdFZ
https://pastebin.com/Cf4LLKEd
https://pastebin.com/EiNK5had
https://pastebin.com/j2XSp6pu
https://pastebin.com/1EM6BSxm
https://pastebin.com/P2Zf7gHn
https://pastebin.com/tjjJFy7s
https://pastebin.com/jZ2QMP9d
https://pastebin.com/vtrnXw8f
https://pastebin.com/rKNy2k7F
https://pastebin.com/t792XJE7
https://pastebin.com/BBb77Pfy
https://pastebin.com/euTtybUX
https://pastebin.com/DDiRxvXw
https://pastebin.com/SpLWzDPF
https://pastebin.com/jVk5exQP
https://pastebin.com/FXCHxBMy
https://pastebin.com/WWUqnR5j
https://pastebin.com/fPQs5mLa
https://pastebin.com/RH5zBVEh
https://pastebin.com/C5w1KpPC
https://pastebin.com/1u6PSz3M
https://pastebin.com/hEWn5WFA
https://pastebin.com/8yH2QWxL
https://pastebin.com/TVdRsjMp
https://pastebin.com/rDbhUfwu
https://pastebin.com/drQEKtGE
https://pastebin.com/99Rmnksr
https://pastebin.com/BXZmvJNc
https://pastebin.com/WG4vFfa5
https://pastebin.com/mMuTtyhm
https://pastebin.com/24dfdEw2
https://pastebin.com/3TkPm4xm
https://pastebin.com/X32JiquQ
https://pastebin.com/j5e9PiRm
https://pastebin.com/cuDaup6h
https://pastebin.com/cwxTRY00
https://pastebin.com/J71r912Y
https://pastebin.com/CzD4M9uD
https://pastebin.com/7KBxgcqK
https://pastebin.com/7NfWAa0J
https://pastebin.com/zwkkUavP
https://pastebin.com/shhZgj5L
https://pastebin.com/H68TdJqL
https://pastebin.com/A5DUFX8G
https://pastebin.com/pbPakzr2
https://pastebin.com/XyVssEmP
https://pastebin.com/wtuvMrT4
https://pastebin.com/w24BpmWr
https://pastebin.com/aiG2D9nf
https://pastebin.com/maNzV2CK
https://pastebin.com/cfE0zNBy
问题现象
如何在画布中心点实现Matrix2D图形指定倍数的放大和指定角度的旋转?
背景知识
Matrix2D组件的方法rotate,能够以旋转点为中心、对当前矩阵进行右乘旋转运算,调用公式为:rotate(degree: number, rx?: number, ry?: number),其中degree为旋转角度,rx和ry为旋转中心点相对[0,0]点的水平和垂直方向坐标,如果[0,0]点通过translate发生移动,则以新的点计算相对的rx和ry值。
translate方法能够对当前矩阵进行左乘平移运算,调用公式为:translate(tx?: number, ty?: number)。
scale方法能够对当前矩阵进行右乘缩放运算,调用公式为:scale(sx?: number, sy?: number),其中sx和sy为水平和垂直缩放比例系数。以[0,0]为基准进行缩放,如果[0,0]点通过translate发生移动,则以移动后的点为基准点进行缩放。
解决方案
使用Flex布局将Canvas组件居中显示,创建矩形。
使用rotate方法对矩阵进行旋转操作,旋转角度由angle决定,旋转中心为矩形的中心;使用scale方法对矩阵进行缩放操作,缩放倍数由scaleTimesX和scaleTimesY决定,以中心点为基准进行缩放。rotate和scale存在调用顺序,遵循就近原则,因此需要将scale方法的使用放在rotate上方。
使用translate方法对矩阵进行平移操作,将画布的原点移动到画布的中心,即可将图形移动至画布中心。将经过变换的矩阵应用到CanvasRenderingContext2D对象上。
用fillRect()方法在画布上绘制矩形。
完整示例参考如下:
@Entry
@Component
struct MatrixChange {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private matrix: Matrix2D = new Matrix2D();
x: number = 50; // 图形大小
y: number = 50; // 图形大小
canvasWidth: number = 200; // 画布大小
canvasHeight: number = 200; // 画布大小
scaleTimesX: number = 2; // 缩放设置
scaleTimesY: number = 2; // 缩放设置
angle: number = -30; // 旋转角度
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width(this.canvasWidth)
.height(this.canvasHeight)
.backgroundColor('#0D5AF5')
.onReady(() => {
this.matrix.scaleX = 1;
this.matrix.scaleY = 1;
this.matrix.scale(this.scaleTimesX, this.scaleTimesY);
this.matrix.rotate(this.angle Math.PI / 180, this.x / 2, this.y / 2);
this.matrix.translate(this.canvasWidth / 2, this.canvasHeight / 2);
this.matrix.translate(-this.x this.scaleTimesX / 2, -this.y * this.scaleTimesY / 2);
this.context.setTransform(this.matrix);
this.context.fillRect(0, 0, this.x, this.y);
});
}
.width('100%')
.height('100%');
}
}
总结
Matrix2D图形能够在画布中心点放大指定倍数并旋转指定角度,该功能适用于需要展示图形并对其进行各种变换的场景,例如数据可视化、图形编辑器等。
https://pastebin.com/jYcy8DG4
https://pastebin.com/Hp1sbSaS
https://pastebin.com/hTxV2yyS
https://pastebin.com/TQCjtTcP
https://pastebin.com/JpF1LSct
https://pastebin.com/Fr3XnQdE
https://pastebin.com/yTvhcbNw
https://pastebin.com/hRe1DgNt
https://pastebin.com/M3y1HL1H
https://pastebin.com/VraVGXVf
https://pastebin.com/griS9fnH
https://pastebin.com/pwrdFgiY
https://pastebin.com/Pbn36K7e
https://pastebin.com/7DMANuaz
https://pastebin.com/rHKJdsZT
https://pastebin.com/NLD2BSd3
https://pastebin.com/95Shz0dA
https://pastebin.com/zhphtiyk
https://pastebin.com/3HY6p8t3
https://pastebin.com/XQEtXnKJ
https://pastebin.com/56Zk2nAE
https://pastebin.com/FHzZvcGp
https://pastebin.com/jvCBLRx8
https://pastebin.com/UQ8bqVpS
https://pastebin.com/H5XxuvFD
https://pastebin.com/ZTRtEnKD
https://pastebin.com/DXXEFpJ7
https://pastebin.com/Xz7is4PA
https://pastebin.com/ujgDH7CQ
https://pastebin.com/QXvsH58y
https://pastebin.com/Syp4LL5s
https://pastebin.com/CLgzB5B2
https://pastebin.com/B1P1eZiT
https://pastebin.com/XsyVXiCg
https://pastebin.com/1XCeaqAU
https://pastebin.com/Jw13Rebn
https://pastebin.com/DyCcgNsv
https://pastebin.com/7LEMiQZ2
https://pastebin.com/dS3rfyQ6
https://pastebin.com/wLwm6rp7
https://pastebin.com/4WGjDaH1
https://pastebin.com/zb1zD5aE
https://pastebin.com/c1zNryeR
https://pastebin.com/4s5BeWXh
https://pastebin.com/Ce3nxNXr
https://pastebin.com/cmj5c080
https://pastebin.com/1H5LCdEY
https://pastebin.com/zZkVFh7Q
https://pastebin.com/BBrYWefF
https://pastebin.com/U4vvzbtw
https://pastebin.com/BWKQJ9Bf
https://pastebin.com/B5CXLSym
https://pastebin.com/PebrcV9M
https://pastebin.com/Ee30dGS4
https://pastebin.com/beXkZr16
https://pastebin.com/qfWN2Ryj
https://pastebin.com/c7mAxDum
https://pastebin.com/MpP9YNFU
https://pastebin.com/SQ8jWZqx
https://pastebin.com/9VALda7W
https://pastebin.com/xZ8P3Ks8
https://pastebin.com/niR9ymit
https://pastebin.com/Rv0T6rUx
https://pastebin.com/jAh0PWYa
https://pastebin.com/3wv5Agv8
https://pastebin.com/EtNNfJmj
https://pastebin.com/a9j6TNjC
https://pastebin.com/x6xxPkPX
https://pastebin.com/az8dYRbQ
https://pastebin.com/husRdHb4
https://pastebin.com/ZQw2Pbhx
https://pastebin.com/C59eWK5e
https://pastebin.com/kzcn3KvK
https://pastebin.com/mT8ehVrP
https://pastebin.com/uv3DmK2r
https://pastebin.com/9A90NJRS
https://pastebin.com/nxKRJ6DM
https://pastebin.com/em4D4Psa
https://pastebin.com/sq1LkcWj
https://pastebin.com/X9Qr3LsF
https://pastebin.com/0yhb1G5u
https://pastebin.com/RNBk3wcp
https://pastebin.com/n21GrF8N
https://pastebin.com/BVGGULWt
https://pastebin.com/2LVYSav1
https://pastebin.com/37m2vAg8
https://pastebin.com/YALGJ9Dj
https://pastebin.com/MPrNKc2X
https://pastebin.com/WcQR7d4P
https://pastebin.com/frpzGFbV
https://pastebin.com/MTZN74bH
https://pastebin.com/4XFYvRhd
https://pastebin.com/XEnbVYfF
https://pastebin.com/iGNu6WyC
https://pastebin.com/iC4qCnDP
https://pastebin.com/SubVHQiU
https://pastebin.com/GtmFQfJ6
https://pastebin.com/PqcdaaqX
https://pastebin.com/wbpVhAa4
https://pastebin.com/Gs8c9UJM
https://pastebin.com/rvBJLy48
https://pastebin.com/qJhsAkBV
https://pastebin.com/GsUxwvRp
https://pastebin.com/xhtemkVi
https://pastebin.com/VpcarPwJ
https://pastebin.com/M2MZ4XjZ
https://pastebin.com/1hsmtBAh
https://pastebin.com/FBKiMKLM
https://pastebin.com/TFcszpgY
https://pastebin.com/wZyc488a
https://pastebin.com/eyzX1hF0
https://pastebin.com/pn2C5r5y
https://pastebin.com/dyHRSz7V
https://pastebin.com/qspZ7UVQ
https://pastebin.com/hXZ59vW5
https://pastebin.com/EBymVseu
https://pastebin.com/Pi2qAyiG
https://pastebin.com/r53FkZrX
https://pastebin.com/pBxp5x6P
https://pastebin.com/kRmwv8xX
https://pastebin.com/YPBtC4bD
https://pastebin.com/zaazK0qN
https://pastebin.com/MH9s5BWr
https://pastebin.com/kUWEmtQ3
https://pastebin.com/EiVfHUPQ
https://pastebin.com/F1zDdap8
https://pastebin.com/x6ninbWm
https://pastebin.com/kp5xBGss
https://pastebin.com/X8rLUdJN
https://pastebin.com/V1Zmj7FJ
https://pastebin.com/UheVuGRp
https://pastebin.com/yKHmpBX3
https://pastebin.com/GQaa3tDW
https://pastebin.com/D00GfaUn
https://pastebin.com/2bTz1JVU
https://pastebin.com/hhdmx2bc
https://pastebin.com/KaXVaXRZ
https://pastebin.com/R0R3JCNA
https://pastebin.com/zQGT96rX
https://pastebin.com/cbqQbPyf
https://pastebin.com/6PJN3M7N
https://pastebin.com/k1yeEBr9
https://pastebin.com/GAVHCfGW
https://pastebin.com/V9BDRArR
https://pastebin.com/Ms7giaW9
https://pastebin.com/ddfs4xn7
https://pastebin.com/bhtqrAfp
https://pastebin.com/hCwrGzXp
https://pastebin.com/Cf6NEq1t
https://pastebin.com/i2YZAQTR
https://pastebin.com/PBVaCkjV
https://pastebin.com/CZh9JdFZ
https://pastebin.com/Cf4LLKEd
https://pastebin.com/EiNK5had
https://pastebin.com/j2XSp6pu
https://pastebin.com/1EM6BSxm
https://pastebin.com/P2Zf7gHn
https://pastebin.com/tjjJFy7s
https://pastebin.com/jZ2QMP9d
https://pastebin.com/vtrnXw8f
https://pastebin.com/rKNy2k7F
https://pastebin.com/t792XJE7
https://pastebin.com/BBb77Pfy
https://pastebin.com/euTtybUX
https://pastebin.com/DDiRxvXw
https://pastebin.com/SpLWzDPF
https://pastebin.com/jVk5exQP
https://pastebin.com/FXCHxBMy
https://pastebin.com/WWUqnR5j
https://pastebin.com/fPQs5mLa
https://pastebin.com/RH5zBVEh
https://pastebin.com/C5w1KpPC
https://pastebin.com/1u6PSz3M
https://pastebin.com/hEWn5WFA
https://pastebin.com/8yH2QWxL
https://pastebin.com/TVdRsjMp
https://pastebin.com/rDbhUfwu
https://pastebin.com/drQEKtGE
https://pastebin.com/99Rmnksr
https://pastebin.com/BXZmvJNc
https://pastebin.com/WG4vFfa5
https://pastebin.com/mMuTtyhm
https://pastebin.com/24dfdEw2
https://pastebin.com/3TkPm4xm
https://pastebin.com/X32JiquQ
https://pastebin.com/j5e9PiRm
https://pastebin.com/cuDaup6h
https://pastebin.com/cwxTRY00
https://pastebin.com/J71r912Y
https://pastebin.com/CzD4M9uD
https://pastebin.com/7KBxgcqK
https://pastebin.com/7NfWAa0J
https://pastebin.com/zwkkUavP
https://pastebin.com/shhZgj5L
https://pastebin.com/H68TdJqL
https://pastebin.com/A5DUFX8G
https://pastebin.com/pbPakzr2
https://pastebin.com/XyVssEmP
https://pastebin.com/wtuvMrT4
https://pastebin.com/w24BpmWr
https://pastebin.com/aiG2D9nf
https://pastebin.com/maNzV2CK
https://pastebin.com/cfE0zNBy
如何在不同场景下实现页面置灰效果
问题现象
在不同的场景下,如何实现将单个组件、页面或者整个app置灰的效果,具体场景如下:
场景
场景说明
场景一:单个组件置灰
将单个组件颜色置灰,其他组件不受影响,例如将一张彩色图片变成灰白色图片
场景二:单个页面置灰
在多个页面场景中,只将其中某个页面颜色置灰,其他页面不受影响
场景三:所有页面置灰
将app中的所有页面颜色置灰,例如当发生一些重大事件(哀悼日)时,要求将整个app的页面颜色统一设置为灰色
背景知识
Navigation:路由导航的根视图容器,一般作为Page页面的根容器使用,其内部默认包含了标题栏、内容区和工具栏,其中内容区默认首页显示导航内容(Navigation的子组件)或非首页显示(NavDestination的子组件),首页和非首页通过路由进行切换。
grayscale:为组件添加灰度效果。上层渲染灰度会覆盖下层子组件渲染。值定义为灰度转换的比例,入参1则完全转为灰度图像,入参0则图像无变化,入参在0和1之间时,效果呈线性变化。
saturate:为组件添加饱和度效果,饱和度为颜色中的含色成分和消色成分(灰)的比例,入参为1时,显示原图像,大于1时含色成分越大,饱和度越大,小于1时消色成分越大,饱和度越小。
解决方案
场景一:单个组件置灰。
通过给Image组件添加grayscale属性并将属性值设置为1来实现图片置灰效果,或者使用saturate属性并将属性值设置为0来实现图片置灰效果。示例代码如下:
@Entry
@Component
struct GrayDemo {
@State grayscaleValue: number = 0; // 灰度默认为0,正常显示
@State saturateValue: number = 1; // 饱和度默认为1,正常显示
build() {
Row() {
Column() {
Text('grayscale:')
Image($r('app.media.startIcon'))
.autoResize(true)
.width(100)
.height(100)
.margin(16)
.grayscale(this.grayscaleValue) // 设置图片灰度效果
Button('一键置灰').onClick(() => {
this.grayscaleValue = 1; // 设置灰度为100%
})
Text('saturate:').margin({ top: 16 })
Image($r('app.media.startIcon'))
.autoResize(true)
.width(100)
.height(100)
.margin(16)
.saturate(this.saturateValue) // 设置图片的饱和度
Button('一键置灰').onClick(() => {
this.saturateValue = 0; // 将饱和度设置为0,显示灰白
})
}
}
.justifyContent(FlexAlign.Center)
.alignItems(VerticalAlign.Center)
.width('100%')
.height('100%')
}
}
效果图如下:
点击放大
场景二:单个页面置灰。
在多个页面场景,如果只有某个页面需要置灰,其他页面不变,只需将相应页面根元素设置grayscale属性为1。
首先定义一个变量grayscaleValueSingle,本页面根组件Column设置grayscale属性,分别给用于实现本页面置灰和还原效果的Button绑定onClick事件,该事件用于修改grayscaleValueSingle的值,当该值变化时,即可实现本页面的置灰效果,子页面没有置灰。
效果图如下:
点击放大
场景三:所有页面置灰。Navigation设置的一些属性会影响所有的页面,将主页的Navigation组件设置grayscale属性为1,可实现所有页面置灰的效果。完整示例代码如下:主页Index.ets示例代码如下:
@Entry
@Component
struct Index {
@State grayscaleValueAll: number = 0; // 灰度默认为0,正常显示
@State grayscaleValueSingle: number = 0;
pageStack: NavPathStack = new NavPathStack();
build() {
Navigation(this.pageStack) {
Column() {
Button('前往子页', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.pageStack.pushPathByName('PageOne', null, false);
})
Image($r('app.media.startIcon'))
.width('50%')
.height('30%')
Button('本页面置灰', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.grayscaleValueSingle = 1; // 设置灰度为100%
})
Button('全局置灰', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.onClick(() => {
this.grayscaleValueAll = 1; // 设置灰度为100%
})
Button('还原', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.grayscaleValueAll = 0;
this.grayscaleValueSingle = 0;
})
}.grayscale(this.grayscaleValueSingle)
}
.title('主页')
.grayscale(this.grayscaleValueAll)
}
}
子页PageOne.ets示例代码如下:
@Builder
export function PageOneBuilder() {
PageOne()
}
@Entry
@Component
struct PageOne {
build() {
NavDestination() {
Column() {
Button('这是子页', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
}
.width('100%')
.height('100%')
}
}
}
route_map需放置在项目名/src/main/resources/base/profile/route_map.json路径下,具体代码如下:
{
"routerMap": [
{
"name": "PageOne",
"pageSourceFile": "src/main/ets/pages/PageOne.ets",
"buildFunction": "PageOneBuilder",
"data": {
"description": "This is PageOne"
}
}
]
}
在module.json5配置文件的module标签中定义routerMap字段,指向定义的路由表配置文件route_map.json,如:"routerMap": "$profile:route_map"。
效果图如下:
点击放大
常见FAQ
Q:在Navigation组件中添加的属性,在NavDestination组件中也会生效吗?
A:NavDestination作为子页面的根容器,用于显示Navigation的内容区。NavDestination组件在渲染时会使用到Navigation组件中添加的属性。
https://pastebin.com/tB45X2Jp
https://pastebin.com/hjD1EQe6
https://pastebin.com/ZPZSXrit
https://pastebin.com/BKvXc1XH
https://pastebin.com/EWXDC53c
https://pastebin.com/cZtc3Gm0
https://pastebin.com/D8xdXuhM
https://pastebin.com/EgrbEUJD
https://pastebin.com/8VvqjShG
https://pastebin.com/C8U16GGp
https://pastebin.com/601zAGr0
https://pastebin.com/VUYU8tTc
https://pastebin.com/4eSAuAFs
https://pastebin.com/hYWauvkZ
https://pastebin.com/dKtpzYwL
https://pastebin.com/faS8dizU
https://pastebin.com/epWAdZjT
https://pastebin.com/N28eTbrZ
https://pastebin.com/4Yhy1g4R
https://pastebin.com/pVHAppet
https://pastebin.com/6n0m31zk
https://pastebin.com/BwNRYEsp
https://pastebin.com/UHgxVZrY
https://pastebin.com/sdBk4pwS
https://pastebin.com/qw3Qeiv3
https://pastebin.com/ZE3yTP0u
https://pastebin.com/fbLvkuFA
https://pastebin.com/jrQByFhQ
https://pastebin.com/BLDqNVZd
https://pastebin.com/rsWambwi
https://pastebin.com/jSNv47wj
https://pastebin.com/SgFwMwCn
https://pastebin.com/ii9Mx19w
https://pastebin.com/U12DCAjc
https://pastebin.com/J4UTSFCv
https://pastebin.com/vLKGZmEC
https://pastebin.com/45sT2V0T
https://pastebin.com/HNSU6w07
https://pastebin.com/Q1ez1SyN
https://pastebin.com/NU2YtB2j
https://pastebin.com/4vYkErDF
https://pastebin.com/HbEs4xd0
https://pastebin.com/EQ5rygX0
https://pastebin.com/56zyx4mu
https://pastebin.com/BxL1hQtN
https://pastebin.com/u95LA4eA
https://pastebin.com/SERQ5L1R
https://pastebin.com/1HLR4hfE
https://pastebin.com/uhYYhvY7
https://pastebin.com/Gzwqu9J8
https://pastebin.com/TRzJAa7C
https://pastebin.com/jkvnkxUf
https://pastebin.com/tQniYitM
https://pastebin.com/teftqPhB
https://pastebin.com/ghmm3Z45
https://pastebin.com/u8zhaGJe
https://pastebin.com/pBUjLT6a
https://pastebin.com/F8xircWV
https://pastebin.com/bHfQyddL
https://pastebin.com/US11UXan
https://pastebin.com/uUq8A9PG
https://pastebin.com/gf0TnLaX
https://pastebin.com/KbjDei75
https://pastebin.com/Eg8SBXip
https://pastebin.com/TRnQT00H
https://pastebin.com/hrJTVPDq
https://pastebin.com/FQybjNNY
https://pastebin.com/vkjZ4wN3
https://pastebin.com/Em0EVbKz
https://pastebin.com/8SQtnCqe
https://pastebin.com/JzVba9rR
https://pastebin.com/VYum9agp
https://pastebin.com/kkQzAQQb
https://pastebin.com/rupgeDSt
https://pastebin.com/zaLpEv2s
https://pastebin.com/GcbHRNFi
https://pastebin.com/bpp4uE8Z
https://pastebin.com/7HKMVmd2
https://pastebin.com/Fg7cmq4m
https://pastebin.com/4yzireaB
https://pastebin.com/8JxAZZaT
https://pastebin.com/Ja0YVzXd
https://pastebin.com/ZD0SeiaT
https://pastebin.com/03wkfuNw
https://pastebin.com/2LsPES0D
https://pastebin.com/kpcMTN8H
https://pastebin.com/wDTn15yX
https://pastebin.com/DpmFJRhA
https://pastebin.com/WSgL8jW4
https://pastebin.com/XpDeHfFU
https://pastebin.com/HwhXqV7d
https://pastebin.com/KQuJBJGJ
https://pastebin.com/PvAf8UmX
https://pastebin.com/NvrpD52h
https://pastebin.com/mVcns0hQ
https://pastebin.com/iHkN8Zqt
https://pastebin.com/CtB7EXHR
https://pastebin.com/LGWxiLVh
https://pastebin.com/e1yYzpGV
https://pastebin.com/r690DqD6
https://pastebin.com/dxHZMZpR
https://pastebin.com/9Bt6QmGx
https://pastebin.com/3GR4wnyg
https://pastebin.com/U48VGWDZ
https://pastebin.com/DsvcvGfg
https://pastebin.com/5mJKbEHB
https://pastebin.com/XJHSbEB5
https://pastebin.com/K2TCyawf
https://pastebin.com/Ewn4DHM5
https://pastebin.com/Ta7ufBT4
https://pastebin.com/atf8fKFA
https://pastebin.com/SCwnf7Kq
https://pastebin.com/WwPcSmwn
https://pastebin.com/u1BUyfCp
https://pastebin.com/MdTnRfHn
https://pastebin.com/EbeshHhc
https://pastebin.com/qGcygDuP
https://pastebin.com/SqRmqdgU
https://pastebin.com/7npW5utw
https://pastebin.com/GjSNL297
https://pastebin.com/unDuaQRL
https://pastebin.com/GW5NYdDa
https://pastebin.com/v7NDFUPc
https://pastebin.com/8VRW7Q9K
https://pastebin.com/2KXX6VGt
https://pastebin.com/MCmswb3v
https://pastebin.com/iiuA6adw
https://pastebin.com/D58m3xJB
https://pastebin.com/0S5C0W5s
https://pastebin.com/kd37nDY6
https://pastebin.com/THKnHxWN
https://pastebin.com/b0cNSgs9
https://pastebin.com/4EgxXbvr
https://pastebin.com/e0Y46BLB
https://pastebin.com/JYnQsScA
https://pastebin.com/0JHz4u7D
https://pastebin.com/eLygzWDz
https://pastebin.com/BpNaLvtM
https://pastebin.com/YEpynedk
https://pastebin.com/nr92i4cm
https://pastebin.com/GyJdL3jT
https://pastebin.com/5J59xjwP
https://pastebin.com/YzKHrHf8
https://pastebin.com/9e9Fw0qZ
https://pastebin.com/xeyWtjCZ
https://pastebin.com/ZuNfjEXd
https://pastebin.com/1eAXJXch
https://pastebin.com/wScAwcxA
https://pastebin.com/veLVP8JY
https://pastebin.com/gp9ivT1n
https://pastebin.com/09pRUVcp
https://pastebin.com/KDpZcsSs
https://pastebin.com/qPuKxaGF
https://pastebin.com/Z1HRFRjF
https://pastebin.com/jR9E2zAk
https://pastebin.com/E42XsidQ
https://pastebin.com/vnpF0CrJ
https://pastebin.com/tPdeYkh9
https://pastebin.com/SvdMHSSw
https://pastebin.com/8vBeN0S8
https://pastebin.com/B6WRVRQ4
https://pastebin.com/zydaXiMd
https://pastebin.com/nsb4NEC3
https://pastebin.com/QxyaK9dt
https://pastebin.com/aztZVSES
https://pastebin.com/gq0Ugnzu
https://pastebin.com/WQKjeyU6
https://pastebin.com/JjqU9JHd
https://pastebin.com/m8x0g5jW
https://pastebin.com/5nbWUgFh
https://pastebin.com/Rzgpje7d
https://pastebin.com/K0wf5rAY
https://pastebin.com/ZDPfudPN
https://pastebin.com/RSxAxA0k
https://pastebin.com/WwvnWgmu
https://pastebin.com/pGpEm8MC
https://pastebin.com/yeGNby1Y
https://pastebin.com/G0i3MQkj
https://pastebin.com/te38JUac
https://pastebin.com/dDmpLYkT
https://pastebin.com/a6eywsqw
https://pastebin.com/u2aXcVQm
https://pastebin.com/ECmeMX9f
https://pastebin.com/VcR7W9zx
https://pastebin.com/XRU0XdJV
https://pastebin.com/vrr5hgAv
https://pastebin.com/fRf4Uz2n
https://pastebin.com/wNUGRHMQ
https://pastebin.com/yVnHymtb
https://pastebin.com/gQWJU5a2
https://pastebin.com/VfquXqXb
https://pastebin.com/k1bQrXjs
https://pastebin.com/2BRqX78a
https://pastebin.com/qhfE1Qni
https://pastebin.com/uxwXhuAJ
https://pastebin.com/Z68kDKtq
https://pastebin.com/DUsNuWn8
https://pastebin.com/ALf4SeRQ
https://pastebin.com/6922Wz0j
https://pastebin.com/GwpbvjZw
https://pastebin.com/psciSpxN
https://pastebin.com/3gZnEA2Q
https://pastebin.com/n0cwrgXU
https://pastebin.com/hq907uQR
https://pastebin.com/9VehTSWL
https://pastebin.com/8UE4KeVN
问题现象
在不同的场景下,如何实现将单个组件、页面或者整个app置灰的效果,具体场景如下:
场景
场景说明
场景一:单个组件置灰
将单个组件颜色置灰,其他组件不受影响,例如将一张彩色图片变成灰白色图片
场景二:单个页面置灰
在多个页面场景中,只将其中某个页面颜色置灰,其他页面不受影响
场景三:所有页面置灰
将app中的所有页面颜色置灰,例如当发生一些重大事件(哀悼日)时,要求将整个app的页面颜色统一设置为灰色
背景知识
Navigation:路由导航的根视图容器,一般作为Page页面的根容器使用,其内部默认包含了标题栏、内容区和工具栏,其中内容区默认首页显示导航内容(Navigation的子组件)或非首页显示(NavDestination的子组件),首页和非首页通过路由进行切换。
grayscale:为组件添加灰度效果。上层渲染灰度会覆盖下层子组件渲染。值定义为灰度转换的比例,入参1则完全转为灰度图像,入参0则图像无变化,入参在0和1之间时,效果呈线性变化。
saturate:为组件添加饱和度效果,饱和度为颜色中的含色成分和消色成分(灰)的比例,入参为1时,显示原图像,大于1时含色成分越大,饱和度越大,小于1时消色成分越大,饱和度越小。
解决方案
场景一:单个组件置灰。
通过给Image组件添加grayscale属性并将属性值设置为1来实现图片置灰效果,或者使用saturate属性并将属性值设置为0来实现图片置灰效果。示例代码如下:
@Entry
@Component
struct GrayDemo {
@State grayscaleValue: number = 0; // 灰度默认为0,正常显示
@State saturateValue: number = 1; // 饱和度默认为1,正常显示
build() {
Row() {
Column() {
Text('grayscale:')
Image($r('app.media.startIcon'))
.autoResize(true)
.width(100)
.height(100)
.margin(16)
.grayscale(this.grayscaleValue) // 设置图片灰度效果
Button('一键置灰').onClick(() => {
this.grayscaleValue = 1; // 设置灰度为100%
})
Text('saturate:').margin({ top: 16 })
Image($r('app.media.startIcon'))
.autoResize(true)
.width(100)
.height(100)
.margin(16)
.saturate(this.saturateValue) // 设置图片的饱和度
Button('一键置灰').onClick(() => {
this.saturateValue = 0; // 将饱和度设置为0,显示灰白
})
}
}
.justifyContent(FlexAlign.Center)
.alignItems(VerticalAlign.Center)
.width('100%')
.height('100%')
}
}
效果图如下:
点击放大
场景二:单个页面置灰。
在多个页面场景,如果只有某个页面需要置灰,其他页面不变,只需将相应页面根元素设置grayscale属性为1。
首先定义一个变量grayscaleValueSingle,本页面根组件Column设置grayscale属性,分别给用于实现本页面置灰和还原效果的Button绑定onClick事件,该事件用于修改grayscaleValueSingle的值,当该值变化时,即可实现本页面的置灰效果,子页面没有置灰。
效果图如下:
点击放大
场景三:所有页面置灰。Navigation设置的一些属性会影响所有的页面,将主页的Navigation组件设置grayscale属性为1,可实现所有页面置灰的效果。完整示例代码如下:主页Index.ets示例代码如下:
@Entry
@Component
struct Index {
@State grayscaleValueAll: number = 0; // 灰度默认为0,正常显示
@State grayscaleValueSingle: number = 0;
pageStack: NavPathStack = new NavPathStack();
build() {
Navigation(this.pageStack) {
Column() {
Button('前往子页', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.pageStack.pushPathByName('PageOne', null, false);
})
Image($r('app.media.startIcon'))
.width('50%')
.height('30%')
Button('本页面置灰', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.grayscaleValueSingle = 1; // 设置灰度为100%
})
Button('全局置灰', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.onClick(() => {
this.grayscaleValueAll = 1; // 设置灰度为100%
})
Button('还原', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
.onClick(() => {
this.grayscaleValueAll = 0;
this.grayscaleValueSingle = 0;
})
}.grayscale(this.grayscaleValueSingle)
}
.title('主页')
.grayscale(this.grayscaleValueAll)
}
}
子页PageOne.ets示例代码如下:
@Builder
export function PageOneBuilder() {
PageOne()
}
@Entry
@Component
struct PageOne {
build() {
NavDestination() {
Column() {
Button('这是子页', { stateEffect: true, type: ButtonType.Capsule })
.width('80%')
.height(40)
.margin(20)
}
.width('100%')
.height('100%')
}
}
}
route_map需放置在项目名/src/main/resources/base/profile/route_map.json路径下,具体代码如下:
{
"routerMap": [
{
"name": "PageOne",
"pageSourceFile": "src/main/ets/pages/PageOne.ets",
"buildFunction": "PageOneBuilder",
"data": {
"description": "This is PageOne"
}
}
]
}
在module.json5配置文件的module标签中定义routerMap字段,指向定义的路由表配置文件route_map.json,如:"routerMap": "$profile:route_map"。
效果图如下:
点击放大
常见FAQ
Q:在Navigation组件中添加的属性,在NavDestination组件中也会生效吗?
A:NavDestination作为子页面的根容器,用于显示Navigation的内容区。NavDestination组件在渲染时会使用到Navigation组件中添加的属性。
https://pastebin.com/tB45X2Jp
https://pastebin.com/hjD1EQe6
https://pastebin.com/ZPZSXrit
https://pastebin.com/BKvXc1XH
https://pastebin.com/EWXDC53c
https://pastebin.com/cZtc3Gm0
https://pastebin.com/D8xdXuhM
https://pastebin.com/EgrbEUJD
https://pastebin.com/8VvqjShG
https://pastebin.com/C8U16GGp
https://pastebin.com/601zAGr0
https://pastebin.com/VUYU8tTc
https://pastebin.com/4eSAuAFs
https://pastebin.com/hYWauvkZ
https://pastebin.com/dKtpzYwL
https://pastebin.com/faS8dizU
https://pastebin.com/epWAdZjT
https://pastebin.com/N28eTbrZ
https://pastebin.com/4Yhy1g4R
https://pastebin.com/pVHAppet
https://pastebin.com/6n0m31zk
https://pastebin.com/BwNRYEsp
https://pastebin.com/UHgxVZrY
https://pastebin.com/sdBk4pwS
https://pastebin.com/qw3Qeiv3
https://pastebin.com/ZE3yTP0u
https://pastebin.com/fbLvkuFA
https://pastebin.com/jrQByFhQ
https://pastebin.com/BLDqNVZd
https://pastebin.com/rsWambwi
https://pastebin.com/jSNv47wj
https://pastebin.com/SgFwMwCn
https://pastebin.com/ii9Mx19w
https://pastebin.com/U12DCAjc
https://pastebin.com/J4UTSFCv
https://pastebin.com/vLKGZmEC
https://pastebin.com/45sT2V0T
https://pastebin.com/HNSU6w07
https://pastebin.com/Q1ez1SyN
https://pastebin.com/NU2YtB2j
https://pastebin.com/4vYkErDF
https://pastebin.com/HbEs4xd0
https://pastebin.com/EQ5rygX0
https://pastebin.com/56zyx4mu
https://pastebin.com/BxL1hQtN
https://pastebin.com/u95LA4eA
https://pastebin.com/SERQ5L1R
https://pastebin.com/1HLR4hfE
https://pastebin.com/uhYYhvY7
https://pastebin.com/Gzwqu9J8
https://pastebin.com/TRzJAa7C
https://pastebin.com/jkvnkxUf
https://pastebin.com/tQniYitM
https://pastebin.com/teftqPhB
https://pastebin.com/ghmm3Z45
https://pastebin.com/u8zhaGJe
https://pastebin.com/pBUjLT6a
https://pastebin.com/F8xircWV
https://pastebin.com/bHfQyddL
https://pastebin.com/US11UXan
https://pastebin.com/uUq8A9PG
https://pastebin.com/gf0TnLaX
https://pastebin.com/KbjDei75
https://pastebin.com/Eg8SBXip
https://pastebin.com/TRnQT00H
https://pastebin.com/hrJTVPDq
https://pastebin.com/FQybjNNY
https://pastebin.com/vkjZ4wN3
https://pastebin.com/Em0EVbKz
https://pastebin.com/8SQtnCqe
https://pastebin.com/JzVba9rR
https://pastebin.com/VYum9agp
https://pastebin.com/kkQzAQQb
https://pastebin.com/rupgeDSt
https://pastebin.com/zaLpEv2s
https://pastebin.com/GcbHRNFi
https://pastebin.com/bpp4uE8Z
https://pastebin.com/7HKMVmd2
https://pastebin.com/Fg7cmq4m
https://pastebin.com/4yzireaB
https://pastebin.com/8JxAZZaT
https://pastebin.com/Ja0YVzXd
https://pastebin.com/ZD0SeiaT
https://pastebin.com/03wkfuNw
https://pastebin.com/2LsPES0D
https://pastebin.com/kpcMTN8H
https://pastebin.com/wDTn15yX
https://pastebin.com/DpmFJRhA
https://pastebin.com/WSgL8jW4
https://pastebin.com/XpDeHfFU
https://pastebin.com/HwhXqV7d
https://pastebin.com/KQuJBJGJ
https://pastebin.com/PvAf8UmX
https://pastebin.com/NvrpD52h
https://pastebin.com/mVcns0hQ
https://pastebin.com/iHkN8Zqt
https://pastebin.com/CtB7EXHR
https://pastebin.com/LGWxiLVh
https://pastebin.com/e1yYzpGV
https://pastebin.com/r690DqD6
https://pastebin.com/dxHZMZpR
https://pastebin.com/9Bt6QmGx
https://pastebin.com/3GR4wnyg
https://pastebin.com/U48VGWDZ
https://pastebin.com/DsvcvGfg
https://pastebin.com/5mJKbEHB
https://pastebin.com/XJHSbEB5
https://pastebin.com/K2TCyawf
https://pastebin.com/Ewn4DHM5
https://pastebin.com/Ta7ufBT4
https://pastebin.com/atf8fKFA
https://pastebin.com/SCwnf7Kq
https://pastebin.com/WwPcSmwn
https://pastebin.com/u1BUyfCp
https://pastebin.com/MdTnRfHn
https://pastebin.com/EbeshHhc
https://pastebin.com/qGcygDuP
https://pastebin.com/SqRmqdgU
https://pastebin.com/7npW5utw
https://pastebin.com/GjSNL297
https://pastebin.com/unDuaQRL
https://pastebin.com/GW5NYdDa
https://pastebin.com/v7NDFUPc
https://pastebin.com/8VRW7Q9K
https://pastebin.com/2KXX6VGt
https://pastebin.com/MCmswb3v
https://pastebin.com/iiuA6adw
https://pastebin.com/D58m3xJB
https://pastebin.com/0S5C0W5s
https://pastebin.com/kd37nDY6
https://pastebin.com/THKnHxWN
https://pastebin.com/b0cNSgs9
https://pastebin.com/4EgxXbvr
https://pastebin.com/e0Y46BLB
https://pastebin.com/JYnQsScA
https://pastebin.com/0JHz4u7D
https://pastebin.com/eLygzWDz
https://pastebin.com/BpNaLvtM
https://pastebin.com/YEpynedk
https://pastebin.com/nr92i4cm
https://pastebin.com/GyJdL3jT
https://pastebin.com/5J59xjwP
https://pastebin.com/YzKHrHf8
https://pastebin.com/9e9Fw0qZ
https://pastebin.com/xeyWtjCZ
https://pastebin.com/ZuNfjEXd
https://pastebin.com/1eAXJXch
https://pastebin.com/wScAwcxA
https://pastebin.com/veLVP8JY
https://pastebin.com/gp9ivT1n
https://pastebin.com/09pRUVcp
https://pastebin.com/KDpZcsSs
https://pastebin.com/qPuKxaGF
https://pastebin.com/Z1HRFRjF
https://pastebin.com/jR9E2zAk
https://pastebin.com/E42XsidQ
https://pastebin.com/vnpF0CrJ
https://pastebin.com/tPdeYkh9
https://pastebin.com/SvdMHSSw
https://pastebin.com/8vBeN0S8
https://pastebin.com/B6WRVRQ4
https://pastebin.com/zydaXiMd
https://pastebin.com/nsb4NEC3
https://pastebin.com/QxyaK9dt
https://pastebin.com/aztZVSES
https://pastebin.com/gq0Ugnzu
https://pastebin.com/WQKjeyU6
https://pastebin.com/JjqU9JHd
https://pastebin.com/m8x0g5jW
https://pastebin.com/5nbWUgFh
https://pastebin.com/Rzgpje7d
https://pastebin.com/K0wf5rAY
https://pastebin.com/ZDPfudPN
https://pastebin.com/RSxAxA0k
https://pastebin.com/WwvnWgmu
https://pastebin.com/pGpEm8MC
https://pastebin.com/yeGNby1Y
https://pastebin.com/G0i3MQkj
https://pastebin.com/te38JUac
https://pastebin.com/dDmpLYkT
https://pastebin.com/a6eywsqw
https://pastebin.com/u2aXcVQm
https://pastebin.com/ECmeMX9f
https://pastebin.com/VcR7W9zx
https://pastebin.com/XRU0XdJV
https://pastebin.com/vrr5hgAv
https://pastebin.com/fRf4Uz2n
https://pastebin.com/wNUGRHMQ
https://pastebin.com/yVnHymtb
https://pastebin.com/gQWJU5a2
https://pastebin.com/VfquXqXb
https://pastebin.com/k1bQrXjs
https://pastebin.com/2BRqX78a
https://pastebin.com/qhfE1Qni
https://pastebin.com/uxwXhuAJ
https://pastebin.com/Z68kDKtq
https://pastebin.com/DUsNuWn8
https://pastebin.com/ALf4SeRQ
https://pastebin.com/6922Wz0j
https://pastebin.com/GwpbvjZw
https://pastebin.com/psciSpxN
https://pastebin.com/3gZnEA2Q
https://pastebin.com/n0cwrgXU
https://pastebin.com/hq907uQR
https://pastebin.com/9VehTSWL
https://pastebin.com/8UE4KeVN
如何解决CustomDialog内嵌套Navigation导致弹窗无法底部对齐的问题
问题现象
当CustomDialog内部嵌套Navigation容器时,弹窗设置底部显示alignment: DialogAlignment.Bottom时失效,问题代码如下:
@CustomDialog
export struct MyDialog {
controller: CustomDialogController;
build() {
Navigation() {
Column() {
Text('我是弹窗')
.margin({ top: 20 });
}
.width('100%')
.height(200)
.backgroundColor(Color.White);
};
}
}
@Entry
@Component
struct Dialog {
myDiaController: CustomDialogController = new CustomDialogController({
builder: MyDialog({}),
customStyle: true, // 弹窗容器样式是否自定义
autoCancel: false, // 是否允许点击遮障层退出
alignment: DialogAlignment.Bottom, // 弹窗在竖直方向上的对齐,底部对齐失效
});
onPageShow(): void {
this.myDiaController.open();
}
build() {
}
}
问题现象如下:
点击放大
背景知识
CustomDialog:是一种常见的自定义弹窗方式,当其内部嵌套Navigation容器时,Navigation容器在不设置高度的情况下会默认撑满屏幕,而Navigation内部默认至上而下显示,所以导致弹窗的底部显示命令在显示效果上没有生效。
解决方案
由于Navigation在不设置高度时,默认撑满整个手机屏幕,导致嵌套Navigation的弹窗也是全屏显示,从而导致DialogAlignment.Bottom从体验上未生效。实际逻辑是弹窗已经是全屏显示,弹窗底部对齐后依旧是全屏显示。
为Navigation容器设置高度限制(本示例设置300vp),并设置背景颜色为蓝色后,可以发现弹窗为底部对齐效果:
@CustomDialog
export struct MyDialog {
controller: CustomDialogController;
pathStack: NavPathStack = new NavPathStack();
build() {
// 弹窗内使用Navigation可实现弹窗内路由跳转,从而更换弹窗内显示的页面
Navigation(this.pathStack) {
Column() {
Text('我是弹窗')
.margin({ top: 20 });
}
.width('100%')
.height(200)
.backgroundColor(Color.White);
}
.height(300)
.backgroundColor('#0a59f7');
}
}
@Entry
@Component
struct DialogDemo {
myDialogController: CustomDialogController = new CustomDialogController({
builder: MyDialog({}),
customStyle: true, // 弹窗容器样式是否自定义
autoCancel: false, // 是否允许点击遮障层退出
alignment: DialogAlignment.Bottom, // 弹窗在竖直方向上的对齐,底部对齐失效
});
onPageShow(): void {
this.myDialogController.open();
}
build() {
}
}
实现效果如下:
点击放大
上图中弹窗为白色与蓝色部分(其中白色是弹窗中子组件背景色,蓝色是弹窗背景色),弹窗底部对齐。
总结
多数情况下,父容器的大小在未设置尺寸限制的情况下默认自适应子组件大小,所以,该思维惯性会陷入一个误区:默认Navigation容器未设置尺寸时会自适应其子组件Column的高度200vp,从而默认弹窗高度是200vp、底部对齐命令未生效。而实际上,部分容器在未设置尺寸限制时会默认全屏显示,例如Navigation、Tabs等。
https://pastebin.com/WJ5W0twm
https://pastebin.com/jLpfh6jM
https://pastebin.com/NjyZTRcj
https://pastebin.com/Ez67aS1j
https://pastebin.com/PWLApZGh
https://pastebin.com/kgcxtYRV
https://pastebin.com/zm7shgpT
https://pastebin.com/Hs9GycZW
https://pastebin.com/7vv5yCtq
https://pastebin.com/ZS9f3J4Y
https://pastebin.com/46rvnNrr
https://pastebin.com/NwPLquMj
https://pastebin.com/MvzT3WtH
https://pastebin.com/s7291Kt8
https://pastebin.com/xRq94uf9
https://pastebin.com/uMBCp2ev
https://pastebin.com/BWMV3JqP
https://pastebin.com/XPfp8bc9
https://pastebin.com/nKfsMJA5
https://pastebin.com/aKp1dGqk
https://pastebin.com/h2EmDCVE
https://pastebin.com/rZVpf79t
https://pastebin.com/e0rWL4nZ
https://pastebin.com/T1rBGcwT
https://pastebin.com/GW3cpe4h
https://pastebin.com/7L9MDU8B
https://pastebin.com/DdCFC9uX
https://pastebin.com/H6JCTycv
https://pastebin.com/2rF8HFxn
https://pastebin.com/27LRXmHN
https://pastebin.com/vZNhsMEz
https://pastebin.com/EUv3D6T5
https://pastebin.com/DhBRDNpd
https://pastebin.com/LJQy75bK
https://pastebin.com/8Thp0a3g
https://pastebin.com/mHTr3cC7
https://pastebin.com/9ceFaWS0
https://pastebin.com/XfLnUar9
https://pastebin.com/2Ktya3Wm
https://pastebin.com/mMC8tKu4
https://pastebin.com/GGXKYc2R
https://pastebin.com/KjeqQ7WL
https://pastebin.com/pgkpMu3E
https://pastebin.com/WrTGvh8T
https://pastebin.com/PTmNxwCM
https://pastebin.com/nYB5PuJ3
https://pastebin.com/cPwhmWyN
https://pastebin.com/sfACvBXT
https://pastebin.com/BdWfvQ4M
https://pastebin.com/6Y4DCw3k
https://pastebin.com/uiiHmdFq
https://pastebin.com/epBnZPYr
https://pastebin.com/pzrtCDpT
https://pastebin.com/8Y7NGzus
https://pastebin.com/nEh0yKwb
https://pastebin.com/1y8Pauz0
https://pastebin.com/VBdFdQAX
https://pastebin.com/Gzsyyvan
https://pastebin.com/d6KRbrEp
https://pastebin.com/digDdLJy
https://pastebin.com/vXZwSt7S
https://pastebin.com/PFArZUea
https://pastebin.com/fbtycRsf
https://pastebin.com/hZy1Ej5X
https://pastebin.com/q5Ux9M5v
https://pastebin.com/QpqL4m8e
https://pastebin.com/ryZX354t
https://pastebin.com/7fLHzGaX
https://pastebin.com/AK4yYQ8V
https://pastebin.com/K9h66hwy
https://pastebin.com/nsVap5H0
https://pastebin.com/swvzwCcG
https://pastebin.com/DWzPDMcY
https://pastebin.com/rZjvixYp
https://pastebin.com/MJAQGYNi
https://pastebin.com/gr2HUq25
https://pastebin.com/G59auG15
https://pastebin.com/USKWbQEt
https://pastebin.com/FCWwERJp
https://pastebin.com/pk8Mg2gd
https://pastebin.com/EweSwHmL
https://pastebin.com/NgbmDKYh
https://pastebin.com/dA414jhS
https://pastebin.com/4DP40dP2
https://pastebin.com/8wJ89BfG
https://pastebin.com/np7qgdcd
https://pastebin.com/waRHhrn0
https://pastebin.com/XfgUtMpu
https://pastebin.com/H2Gn2Cd2
https://pastebin.com/YghYQ0uy
https://pastebin.com/gj198nVk
https://pastebin.com/BMvr1bRK
https://pastebin.com/stJjWb7K
https://pastebin.com/PgV71Qx1
https://pastebin.com/rjS5iJhU
https://pastebin.com/naLAjPCs
https://pastebin.com/9Zd4qDyw
https://pastebin.com/NF88dyqv
https://pastebin.com/TyG5AVCY
https://pastebin.com/09sR3TSA
https://pastebin.com/GMCCXfv4
https://pastebin.com/ekY0AWb5
https://pastebin.com/ydiwskGD
https://pastebin.com/dVAGRzeJ
https://pastebin.com/iPPHqvfH
https://pastebin.com/w2dhvkWf
https://pastebin.com/mJdRLzGT
https://pastebin.com/c0bQVCVG
https://pastebin.com/QxWJcQAE
https://pastebin.com/URvark7U
https://pastebin.com/HYmjV2sW
https://pastebin.com/dxAu9Mws
https://pastebin.com/TqsS1fuf
https://pastebin.com/fD3GdwWA
https://pastebin.com/eummuY4R
https://pastebin.com/Zi6pLB5b
https://pastebin.com/AGrFQH97
https://pastebin.com/JAXJz8ue
https://pastebin.com/vDcgWd7V
https://pastebin.com/Ny9Rpnqc
https://pastebin.com/FHC1TNwz
https://pastebin.com/DAm7ysS3
https://pastebin.com/XT3ukakt
https://pastebin.com/Y8rD5b75
https://pastebin.com/p1ywR3cC
https://pastebin.com/8Bf036kt
https://pastebin.com/jQVftHBx
https://pastebin.com/n3AC806q
https://pastebin.com/HaQjLjxt
https://pastebin.com/Az91WjQy
https://pastebin.com/TuQUMZxV
https://pastebin.com/xrcq9wBE
https://pastebin.com/XUSJaa6K
https://pastebin.com/kmRpMKVd
https://pastebin.com/vJrrEp4a
https://pastebin.com/aMHtNZwQ
https://pastebin.com/hj0XLquF
https://pastebin.com/10MqCtqC
https://pastebin.com/diTK3Pbx
https://pastebin.com/8cgt7F7S
https://pastebin.com/e1VQgBmN
https://pastebin.com/fXUSWCNx
https://pastebin.com/r7rQyL9M
https://pastebin.com/21AGukpK
https://pastebin.com/g5a4KjRk
https://pastebin.com/Gha4HHQa
https://pastebin.com/UVUx04a9
https://pastebin.com/UZ8wV9iD
https://pastebin.com/fBLkWarW
https://pastebin.com/9AxDJFZh
https://pastebin.com/Ccapyvbv
https://pastebin.com/GHkYrv7E
https://pastebin.com/nLvZnY0S
https://pastebin.com/UyxZ5bTB
https://pastebin.com/nDtYHgrc
https://pastebin.com/HPsCHN5d
https://pastebin.com/cBLNxnW1
https://pastebin.com/EhH7qWW2
https://pastebin.com/ARGDwZDM
https://pastebin.com/Efm309DL
https://pastebin.com/Nty90f6F
https://pastebin.com/5vzhFkmH
https://pastebin.com/QhaJcfCq
https://pastebin.com/G6WKRLhJ
https://pastebin.com/8iWWkQ0i
https://pastebin.com/cWQWa4sy
https://pastebin.com/6KBPeVqL
问题现象
当CustomDialog内部嵌套Navigation容器时,弹窗设置底部显示alignment: DialogAlignment.Bottom时失效,问题代码如下:
@CustomDialog
export struct MyDialog {
controller: CustomDialogController;
build() {
Navigation() {
Column() {
Text('我是弹窗')
.margin({ top: 20 });
}
.width('100%')
.height(200)
.backgroundColor(Color.White);
};
}
}
@Entry
@Component
struct Dialog {
myDiaController: CustomDialogController = new CustomDialogController({
builder: MyDialog({}),
customStyle: true, // 弹窗容器样式是否自定义
autoCancel: false, // 是否允许点击遮障层退出
alignment: DialogAlignment.Bottom, // 弹窗在竖直方向上的对齐,底部对齐失效
});
onPageShow(): void {
this.myDiaController.open();
}
build() {
}
}
问题现象如下:
点击放大
背景知识
CustomDialog:是一种常见的自定义弹窗方式,当其内部嵌套Navigation容器时,Navigation容器在不设置高度的情况下会默认撑满屏幕,而Navigation内部默认至上而下显示,所以导致弹窗的底部显示命令在显示效果上没有生效。
解决方案
由于Navigation在不设置高度时,默认撑满整个手机屏幕,导致嵌套Navigation的弹窗也是全屏显示,从而导致DialogAlignment.Bottom从体验上未生效。实际逻辑是弹窗已经是全屏显示,弹窗底部对齐后依旧是全屏显示。
为Navigation容器设置高度限制(本示例设置300vp),并设置背景颜色为蓝色后,可以发现弹窗为底部对齐效果:
@CustomDialog
export struct MyDialog {
controller: CustomDialogController;
pathStack: NavPathStack = new NavPathStack();
build() {
// 弹窗内使用Navigation可实现弹窗内路由跳转,从而更换弹窗内显示的页面
Navigation(this.pathStack) {
Column() {
Text('我是弹窗')
.margin({ top: 20 });
}
.width('100%')
.height(200)
.backgroundColor(Color.White);
}
.height(300)
.backgroundColor('#0a59f7');
}
}
@Entry
@Component
struct DialogDemo {
myDialogController: CustomDialogController = new CustomDialogController({
builder: MyDialog({}),
customStyle: true, // 弹窗容器样式是否自定义
autoCancel: false, // 是否允许点击遮障层退出
alignment: DialogAlignment.Bottom, // 弹窗在竖直方向上的对齐,底部对齐失效
});
onPageShow(): void {
this.myDialogController.open();
}
build() {
}
}
实现效果如下:
点击放大
上图中弹窗为白色与蓝色部分(其中白色是弹窗中子组件背景色,蓝色是弹窗背景色),弹窗底部对齐。
总结
多数情况下,父容器的大小在未设置尺寸限制的情况下默认自适应子组件大小,所以,该思维惯性会陷入一个误区:默认Navigation容器未设置尺寸时会自适应其子组件Column的高度200vp,从而默认弹窗高度是200vp、底部对齐命令未生效。而实际上,部分容器在未设置尺寸限制时会默认全屏显示,例如Navigation、Tabs等。
https://pastebin.com/WJ5W0twm
https://pastebin.com/jLpfh6jM
https://pastebin.com/NjyZTRcj
https://pastebin.com/Ez67aS1j
https://pastebin.com/PWLApZGh
https://pastebin.com/kgcxtYRV
https://pastebin.com/zm7shgpT
https://pastebin.com/Hs9GycZW
https://pastebin.com/7vv5yCtq
https://pastebin.com/ZS9f3J4Y
https://pastebin.com/46rvnNrr
https://pastebin.com/NwPLquMj
https://pastebin.com/MvzT3WtH
https://pastebin.com/s7291Kt8
https://pastebin.com/xRq94uf9
https://pastebin.com/uMBCp2ev
https://pastebin.com/BWMV3JqP
https://pastebin.com/XPfp8bc9
https://pastebin.com/nKfsMJA5
https://pastebin.com/aKp1dGqk
https://pastebin.com/h2EmDCVE
https://pastebin.com/rZVpf79t
https://pastebin.com/e0rWL4nZ
https://pastebin.com/T1rBGcwT
https://pastebin.com/GW3cpe4h
https://pastebin.com/7L9MDU8B
https://pastebin.com/DdCFC9uX
https://pastebin.com/H6JCTycv
https://pastebin.com/2rF8HFxn
https://pastebin.com/27LRXmHN
https://pastebin.com/vZNhsMEz
https://pastebin.com/EUv3D6T5
https://pastebin.com/DhBRDNpd
https://pastebin.com/LJQy75bK
https://pastebin.com/8Thp0a3g
https://pastebin.com/mHTr3cC7
https://pastebin.com/9ceFaWS0
https://pastebin.com/XfLnUar9
https://pastebin.com/2Ktya3Wm
https://pastebin.com/mMC8tKu4
https://pastebin.com/GGXKYc2R
https://pastebin.com/KjeqQ7WL
https://pastebin.com/pgkpMu3E
https://pastebin.com/WrTGvh8T
https://pastebin.com/PTmNxwCM
https://pastebin.com/nYB5PuJ3
https://pastebin.com/cPwhmWyN
https://pastebin.com/sfACvBXT
https://pastebin.com/BdWfvQ4M
https://pastebin.com/6Y4DCw3k
https://pastebin.com/uiiHmdFq
https://pastebin.com/epBnZPYr
https://pastebin.com/pzrtCDpT
https://pastebin.com/8Y7NGzus
https://pastebin.com/nEh0yKwb
https://pastebin.com/1y8Pauz0
https://pastebin.com/VBdFdQAX
https://pastebin.com/Gzsyyvan
https://pastebin.com/d6KRbrEp
https://pastebin.com/digDdLJy
https://pastebin.com/vXZwSt7S
https://pastebin.com/PFArZUea
https://pastebin.com/fbtycRsf
https://pastebin.com/hZy1Ej5X
https://pastebin.com/q5Ux9M5v
https://pastebin.com/QpqL4m8e
https://pastebin.com/ryZX354t
https://pastebin.com/7fLHzGaX
https://pastebin.com/AK4yYQ8V
https://pastebin.com/K9h66hwy
https://pastebin.com/nsVap5H0
https://pastebin.com/swvzwCcG
https://pastebin.com/DWzPDMcY
https://pastebin.com/rZjvixYp
https://pastebin.com/MJAQGYNi
https://pastebin.com/gr2HUq25
https://pastebin.com/G59auG15
https://pastebin.com/USKWbQEt
https://pastebin.com/FCWwERJp
https://pastebin.com/pk8Mg2gd
https://pastebin.com/EweSwHmL
https://pastebin.com/NgbmDKYh
https://pastebin.com/dA414jhS
https://pastebin.com/4DP40dP2
https://pastebin.com/8wJ89BfG
https://pastebin.com/np7qgdcd
https://pastebin.com/waRHhrn0
https://pastebin.com/XfgUtMpu
https://pastebin.com/H2Gn2Cd2
https://pastebin.com/YghYQ0uy
https://pastebin.com/gj198nVk
https://pastebin.com/BMvr1bRK
https://pastebin.com/stJjWb7K
https://pastebin.com/PgV71Qx1
https://pastebin.com/rjS5iJhU
https://pastebin.com/naLAjPCs
https://pastebin.com/9Zd4qDyw
https://pastebin.com/NF88dyqv
https://pastebin.com/TyG5AVCY
https://pastebin.com/09sR3TSA
https://pastebin.com/GMCCXfv4
https://pastebin.com/ekY0AWb5
https://pastebin.com/ydiwskGD
https://pastebin.com/dVAGRzeJ
https://pastebin.com/iPPHqvfH
https://pastebin.com/w2dhvkWf
https://pastebin.com/mJdRLzGT
https://pastebin.com/c0bQVCVG
https://pastebin.com/QxWJcQAE
https://pastebin.com/URvark7U
https://pastebin.com/HYmjV2sW
https://pastebin.com/dxAu9Mws
https://pastebin.com/TqsS1fuf
https://pastebin.com/fD3GdwWA
https://pastebin.com/eummuY4R
https://pastebin.com/Zi6pLB5b
https://pastebin.com/AGrFQH97
https://pastebin.com/JAXJz8ue
https://pastebin.com/vDcgWd7V
https://pastebin.com/Ny9Rpnqc
https://pastebin.com/FHC1TNwz
https://pastebin.com/DAm7ysS3
https://pastebin.com/XT3ukakt
https://pastebin.com/Y8rD5b75
https://pastebin.com/p1ywR3cC
https://pastebin.com/8Bf036kt
https://pastebin.com/jQVftHBx
https://pastebin.com/n3AC806q
https://pastebin.com/HaQjLjxt
https://pastebin.com/Az91WjQy
https://pastebin.com/TuQUMZxV
https://pastebin.com/xrcq9wBE
https://pastebin.com/XUSJaa6K
https://pastebin.com/kmRpMKVd
https://pastebin.com/vJrrEp4a
https://pastebin.com/aMHtNZwQ
https://pastebin.com/hj0XLquF
https://pastebin.com/10MqCtqC
https://pastebin.com/diTK3Pbx
https://pastebin.com/8cgt7F7S
https://pastebin.com/e1VQgBmN
https://pastebin.com/fXUSWCNx
https://pastebin.com/r7rQyL9M
https://pastebin.com/21AGukpK
https://pastebin.com/g5a4KjRk
https://pastebin.com/Gha4HHQa
https://pastebin.com/UVUx04a9
https://pastebin.com/UZ8wV9iD
https://pastebin.com/fBLkWarW
https://pastebin.com/9AxDJFZh
https://pastebin.com/Ccapyvbv
https://pastebin.com/GHkYrv7E
https://pastebin.com/nLvZnY0S
https://pastebin.com/UyxZ5bTB
https://pastebin.com/nDtYHgrc
https://pastebin.com/HPsCHN5d
https://pastebin.com/cBLNxnW1
https://pastebin.com/EhH7qWW2
https://pastebin.com/ARGDwZDM
https://pastebin.com/Efm309DL
https://pastebin.com/Nty90f6F
https://pastebin.com/5vzhFkmH
https://pastebin.com/QhaJcfCq
https://pastebin.com/G6WKRLhJ
https://pastebin.com/8iWWkQ0i
https://pastebin.com/cWQWa4sy
https://pastebin.com/6KBPeVqL
#插件需求# uniapp x实现APP热更新
uniapp x蒸汽模式希望官方出一个 wgt热更新,或是出一个热更新的解决方案,便于APP后期持续开发
uniapp x蒸汽模式希望官方出一个 wgt热更新,或是出一个热更新的解决方案,便于APP后期持续开发
如何实现键盘上方自定义工具栏
问题现象
跟随键盘的工具栏如何实现?
背景知识
自定义弹窗(CustomDialog):通过CustomDialogController类显示自定义弹窗。使用弹窗组件时,优先考虑自定义弹窗,便于弹窗样式与内容的自定义。
defaultFocus:设置当前组件是否为当前页面上的默认焦点。
on('keyboardHeightChange'):开启固定态软键盘高度变化的监听,当软键盘由本窗口唤出并存在重叠区域时通知键盘高度变化。
Stack:堆叠容器,子组件按照顺序依次入栈,后一个子组件覆盖前一个子组件。
alignContent:设置子组件在容器内的对齐方式。该属性与通用属性align同时设置时,后设置的属性生效。
解决方案
针对跟随键盘的工具栏,可采用以下两种实现方案:
方案一:使用CustomDialog组件自定义工具栏。以下示例通过点击文本组件使弹窗自动获焦,设置弹窗从底部弹出,并为弹窗添加弹出与关闭时的过渡动画,以实现跟随键盘的动画效果。
// 自定义对话框组件,用于显示输入框
@CustomDialog
@Component
export struct Dialog {
dialogController: CustomDialogController;
build() {
Column() {
TextInput({ text: '', placeholder: 'input your word...' })
.type(InputType.Normal)
.defaultFocus(true) // 设置为默认聚焦状态
.onBlur(() => {
// 输入框失去焦点时关闭对话框
this.dialogController.close();
})
.height('50%')
.margin({ top: 25, left: 16, right: 16 });
}
.height(100)
.backgroundColor(Color.White);
}
}
@Entry
@Component
struct Index {
message: string = 'Hello World';
// 自定义对话框控制器,配置对话框的显示参数
customDialogController: CustomDialogController = new CustomDialogController({
builder: Dialog(), // 设置对话框内容组件
alignment: DialogAlignment.Bottom, // 对话框从底部弹出
cornerRadius: 0,
customStyle: true,
openAnimation: { duration: 0.001, tempo: 0 }, // 打开弹窗时动画设置
closeAnimation: { duration: 0.001, tempo: 0 }, // 关闭弹窗时动画设置
});
build() {
Column() {
// 点击按钮打开对话框
Text(this.message)
.onClick(() => {
this.customDialogController.open(); // 触发对话框显示
})
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold);
}
.height('100%')
.width('100%');
}
}
效果预览:
点击放大
方案二:自定义工具栏组件,借助堆叠容器Stack进行页面布局,将组件设置为底部横向居中。定义状态变量isVisible以控制自定义工具栏的显示与隐藏:在TextInput组件聚焦时显示,失焦时隐藏。同时,通过on('keyboardHeightChange')方法监听软键盘高度变化,依据键盘高度动态调整自定义工具栏的位置,使其紧贴于键盘上方。
import { window } from '@kit.ArkUI';
@Entry
@Component
struct Index {
message: string = '图文信息区域';
// 控制自定义工具栏组件可见性
@State isVisible: Visibility = Visibility.Hidden;
// 存储键盘高度信息
@State keyboardHeight: string = '0px';
controller: RichEditorController = new RichEditorController();
// 页面加载时监听键盘高度变化
aboutToAppear(): void {
window.getLastWindow(this.getUIContext().getHostContext()).then((win) => {
win.on('keyboardHeightChange', (height) => {
console.info('height' + height.toString());
if (height) {
this.keyboardHeight = height.toString() + 'px'; // 保存键盘高度
this.isVisible = Visibility.Visible; // 显示自定义组件
} else {
this.isVisible = Visibility.Hidden; // 隐藏自定义组件
}
});
});
}
build() {
// 使用Stack布局,底部对齐
Stack({ alignContent: Alignment.Bottom }) {
Column() {
Text(this.message)
.fontSize(52)
.height('90%')
.width('100%')
.textAlign(TextAlign.Center)
.fontColor(Color.Black);
// 操作按钮行
Row() {
Text('点击拉起键盘')
.fontColor(Color.White)
.width('90%')
.height('40')
.backgroundColor('#ff1a73f8')
.borderRadius(20)
.textAlign(TextAlign.Center)
.margin({ left: 16, right: 16 })
.onClick(() => {
this.isVisible = Visibility.Visible; // 显示自定义组件
setTimeout(() => {
focusControl.requestFocus('textArea'); // 焦点切换到输入框
}, 10);
});
}.height('10%').width('100%');
}
.expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.BOTTOM]); // 适配键盘区域
// 遮罩层(点击隐藏自定义)
Column()
.width('100%')
.height('120%')
.opacity(0.5)
.backgroundColor('rgba(0,0,0,0.5)')
.onClick(() => {
this.isVisible = Visibility.Hidden; // 隐藏自定义组件
})
.visibility(this.isVisible)
.expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.BOTTOM, SafeAreaEdge.TOP]);
// 动态加载自定义组件
CommentComponent({ isVisible: this.isVisible, keyboardHeight: this.keyboardHeight });
};
}
// 页面卸载时隐藏自定义组件
aboutToDisappear(): void {
this.isVisible = Visibility.Hidden;
}
}
// 自定义工具栏组件
@Component
struct CommentComponent {
controller: RichEditorController = new RichEditorController();
@Link isVisible: Visibility;
@Link keyboardHeight: string;
build() {
Flex({ direction: FlexDirection.ColumnReverse, justifyContent: FlexAlign.Start, alignItems: ItemAlign.Stretch }) {
Row() {
RichEditor({ controller: this.controller })
.id('textArea') // 设置输入框ID用于焦点控制
.placeholder('喜欢就评论一下吧~', { fontColor: Color.Gray, font: { size: 16, weight: FontWeight.Normal } })
.width('65%');
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.End, alignItems: ItemAlign.Stretch }) {
Image($r('app.media.startIcon')).height(20).constraintSize({ minWidth: 20, maxWidth: 20 });
}
.width(110);
}
.margin({
top: 10,
bottom: this.keyboardHeight, // 根据键盘高度设置动态调整底部边距
left: 10,
right: 10
})
.border({ width: 1 })
.borderRadius(50);
}
.width('100%')
.height(380)
.expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.BOTTOM, SafeAreaEdge.TOP]) // 适配键盘区域
.backgroundColor(Color.White)
.visibility(this.isVisible);
}
}
https://pastebin.com/6KBPeVqL
https://pastebin.com/bN1ddiZp
https://pastebin.com/gtYW43NW
https://pastebin.com/eJcix7ad
https://pastebin.com/HcrRQFtA
https://pastebin.com/XgyPuxHD
https://pastebin.com/263D2tG3
https://pastebin.com/VFXnShya
https://pastebin.com/JcCfedC7
https://pastebin.com/XgiWLKtb
https://pastebin.com/SnA9AdtL
https://pastebin.com/gXXg0rwX
https://pastebin.com/6JGUtchA
https://pastebin.com/ZbTwd0Ua
https://pastebin.com/0s559jyS
https://pastebin.com/FF4bCbp7
https://pastebin.com/rbJciCS7
https://pastebin.com/fMBrbeYx
https://pastebin.com/3ZzHtZqE
https://pastebin.com/xgZc6Wpx
https://pastebin.com/q9MHz0sP
https://pastebin.com/7BGqgqgb
https://pastebin.com/762Emz0H
https://pastebin.com/KS7UgY63
https://pastebin.com/E0CUmHyN
https://pastebin.com/RaxmNbrv
https://pastebin.com/sWGhM2xB
https://pastebin.com/q4USiCDw
https://pastebin.com/XBjfa0Jv
https://pastebin.com/5R6CQqw3
https://pastebin.com/Q7C1fgyH
https://pastebin.com/fBtA7KM6
https://pastebin.com/dZHaQ1uQ
https://pastebin.com/YEKBNnfc
https://pastebin.com/T3fNdkNE
https://pastebin.com/r2YxuAHc
https://pastebin.com/Y1Fzshsu
https://pastebin.com/KJvxU2vN
https://pastebin.com/57egjdLv
https://pastebin.com/VxNKdCta
https://pastebin.com/3YsNKCSd
https://pastebin.com/Wk06JeP9
https://pastebin.com/T2pGjSNZ
https://pastebin.com/M0kVVxRE
https://pastebin.com/7kAYYh9u
https://pastebin.com/uiKRsuLh
https://pastebin.com/XLg7wEiV
https://pastebin.com/Uk7dPXfC
https://pastebin.com/HXaxi2bh
https://pastebin.com/2stztMET
https://pastebin.com/RxKisB4V
https://pastebin.com/ig8KqDGg
https://pastebin.com/cRQ0yb3J
https://pastebin.com/4hR7SdmD
https://pastebin.com/EwmMgWdr
https://pastebin.com/4b5AFeRk
https://pastebin.com/3CFxLac5
https://pastebin.com/mKn2fjXp
https://pastebin.com/BSa8L13Z
https://pastebin.com/NAtqrReY
https://pastebin.com/34KDinEG
https://pastebin.com/YaXZqyZQ
https://pastebin.com/j2MhC6kw
https://pastebin.com/c1n5dn5T
https://pastebin.com/weATT6j7
https://pastebin.com/zV5bp85z
https://pastebin.com/isfmyWk7
https://pastebin.com/S86UAeMg
https://pastebin.com/XkUgvZQW
https://pastebin.com/v9j6jg3T
https://pastebin.com/3ip0M9T8
https://pastebin.com/W9c1w8Xb
https://pastebin.com/jtcypgTt
https://pastebin.com/tgPhxe2L
https://pastebin.com/bs9jzpuL
https://pastebin.com/W8sLLPtk
https://pastebin.com/gJTGQYCL
https://pastebin.com/Qh2u2nkn
https://pastebin.com/EPEHmxwS
https://pastebin.com/y41haJUr
https://pastebin.com/J6cevDf0
https://pastebin.com/24RSFBR0
https://pastebin.com/KZsSaA18
https://pastebin.com/21egpH32
https://pastebin.com/wDziwJnn
https://pastebin.com/QeQvkA9r
https://pastebin.com/icJRn8VJ
https://pastebin.com/WsvP4LwZ
https://pastebin.com/H8nZikEJ
https://pastebin.com/rn2gyWiP
https://pastebin.com/tfehkve3
https://pastebin.com/kn7dX8Fh
https://pastebin.com/Dn1ZfNEV
https://pastebin.com/yy811Lis
https://pastebin.com/QcqL3CXH
https://pastebin.com/QbMe6xXP
https://pastebin.com/NpR2Ra0H
https://pastebin.com/DeevkS6j
https://pastebin.com/yhumdvyC
https://pastebin.com/mHjSzVib
https://pastebin.com/F2wyRKNJ
https://pastebin.com/cc96TLXV
https://pastebin.com/2U1qwTrS
https://pastebin.com/n6hYfTdQ
https://pastebin.com/rhAFXjq6
https://pastebin.com/Hmj59VVm
https://pastebin.com/YmrAxXMU
https://pastebin.com/JBF9n5PL
https://pastebin.com/f21MNNJt
https://pastebin.com/D1hn89Qa
https://pastebin.com/xqdaxD0A
https://pastebin.com/tm2zPQbn
https://pastebin.com/8j3PBMNW
https://pastebin.com/3LcqrmTu
https://pastebin.com/GY4abWzw
https://pastebin.com/9LnRRWuk
https://pastebin.com/N5HJByTK
https://pastebin.com/aaSvnC3j
https://pastebin.com/UYFUHSWk
https://pastebin.com/fcvPwAqU
https://pastebin.com/fS9cgSGG
https://pastebin.com/NP5mQWhJ
https://pastebin.com/em54RVwp
https://pastebin.com/FhSzXrRD
https://pastebin.com/EaU2AmjN
https://pastebin.com/86fScibj
https://pastebin.com/rgPcewwp
https://pastebin.com/FAhu2G96
https://pastebin.com/fU6un6pq
https://pastebin.com/Fmpvt6K9
https://pastebin.com/DMJHzHuW
https://pastebin.com/F39T4W12
https://pastebin.com/9wGgKwMC
https://pastebin.com/xJXUSDnS
https://pastebin.com/FqUGuWTV
https://pastebin.com/Z3ppjriB
https://pastebin.com/A2AQwvEd
https://pastebin.com/tqBWPMe7
https://pastebin.com/LQ3LFEHs
https://pastebin.com/qgkbKhDs
https://pastebin.com/vNvhLWpB
https://pastebin.com/BYu5Twtq
https://pastebin.com/9MapWu1K
https://pastebin.com/DUS2V33c
https://pastebin.com/WSuFmrmW
https://pastebin.com/vKwBpE8f
https://pastebin.com/ARLCtkJy
https://pastebin.com/R0eRbYXX
https://pastebin.com/vzusjTqP
https://pastebin.com/6xQWzuPp
https://pastebin.com/XZsLs6N3
https://pastebin.com/ccCGb1c1
https://pastebin.com/GbxBPVJ6
https://pastebin.com/c6rWM7yT
https://pastebin.com/0fhv7SWU
https://pastebin.com/LCXSxwqu
https://pastebin.com/UKiEaw1b
https://pastebin.com/rR7WFgRd
https://pastebin.com/GMr8Uit3
https://pastebin.com/EeUAEUzt
https://pastebin.com/iMdgtEvx
https://pastebin.com/M54w1AB8
https://pastebin.com/NBenUCdx
https://pastebin.com/gcYXCccc
https://pastebin.com/VKbbyQWT
https://pastebin.com/AjjbCsHT
https://pastebin.com/95MGXGGW
https://pastebin.com/MGSQGvHt
https://pastebin.com/8vVDgwEX
https://pastebin.com/xg8NhUUu
https://pastebin.com/ejAPdK9h
https://pastebin.com/HC44DqUE
https://pastebin.com/AAERa624
https://pastebin.com/TrqEhKJ0
https://pastebin.com/PhRqJLQH
https://pastebin.com/s10g8uCx
https://pastebin.com/a3RKhwkq
https://pastebin.com/PEsA2ngB
问题现象
跟随键盘的工具栏如何实现?
背景知识
自定义弹窗(CustomDialog):通过CustomDialogController类显示自定义弹窗。使用弹窗组件时,优先考虑自定义弹窗,便于弹窗样式与内容的自定义。
defaultFocus:设置当前组件是否为当前页面上的默认焦点。
on('keyboardHeightChange'):开启固定态软键盘高度变化的监听,当软键盘由本窗口唤出并存在重叠区域时通知键盘高度变化。
Stack:堆叠容器,子组件按照顺序依次入栈,后一个子组件覆盖前一个子组件。
alignContent:设置子组件在容器内的对齐方式。该属性与通用属性align同时设置时,后设置的属性生效。
解决方案
针对跟随键盘的工具栏,可采用以下两种实现方案:
方案一:使用CustomDialog组件自定义工具栏。以下示例通过点击文本组件使弹窗自动获焦,设置弹窗从底部弹出,并为弹窗添加弹出与关闭时的过渡动画,以实现跟随键盘的动画效果。
// 自定义对话框组件,用于显示输入框
@CustomDialog
@Component
export struct Dialog {
dialogController: CustomDialogController;
build() {
Column() {
TextInput({ text: '', placeholder: 'input your word...' })
.type(InputType.Normal)
.defaultFocus(true) // 设置为默认聚焦状态
.onBlur(() => {
// 输入框失去焦点时关闭对话框
this.dialogController.close();
})
.height('50%')
.margin({ top: 25, left: 16, right: 16 });
}
.height(100)
.backgroundColor(Color.White);
}
}
@Entry
@Component
struct Index {
message: string = 'Hello World';
// 自定义对话框控制器,配置对话框的显示参数
customDialogController: CustomDialogController = new CustomDialogController({
builder: Dialog(), // 设置对话框内容组件
alignment: DialogAlignment.Bottom, // 对话框从底部弹出
cornerRadius: 0,
customStyle: true,
openAnimation: { duration: 0.001, tempo: 0 }, // 打开弹窗时动画设置
closeAnimation: { duration: 0.001, tempo: 0 }, // 关闭弹窗时动画设置
});
build() {
Column() {
// 点击按钮打开对话框
Text(this.message)
.onClick(() => {
this.customDialogController.open(); // 触发对话框显示
})
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold);
}
.height('100%')
.width('100%');
}
}
效果预览:
点击放大
方案二:自定义工具栏组件,借助堆叠容器Stack进行页面布局,将组件设置为底部横向居中。定义状态变量isVisible以控制自定义工具栏的显示与隐藏:在TextInput组件聚焦时显示,失焦时隐藏。同时,通过on('keyboardHeightChange')方法监听软键盘高度变化,依据键盘高度动态调整自定义工具栏的位置,使其紧贴于键盘上方。
import { window } from '@kit.ArkUI';
@Entry
@Component
struct Index {
message: string = '图文信息区域';
// 控制自定义工具栏组件可见性
@State isVisible: Visibility = Visibility.Hidden;
// 存储键盘高度信息
@State keyboardHeight: string = '0px';
controller: RichEditorController = new RichEditorController();
// 页面加载时监听键盘高度变化
aboutToAppear(): void {
window.getLastWindow(this.getUIContext().getHostContext()).then((win) => {
win.on('keyboardHeightChange', (height) => {
console.info('height' + height.toString());
if (height) {
this.keyboardHeight = height.toString() + 'px'; // 保存键盘高度
this.isVisible = Visibility.Visible; // 显示自定义组件
} else {
this.isVisible = Visibility.Hidden; // 隐藏自定义组件
}
});
});
}
build() {
// 使用Stack布局,底部对齐
Stack({ alignContent: Alignment.Bottom }) {
Column() {
Text(this.message)
.fontSize(52)
.height('90%')
.width('100%')
.textAlign(TextAlign.Center)
.fontColor(Color.Black);
// 操作按钮行
Row() {
Text('点击拉起键盘')
.fontColor(Color.White)
.width('90%')
.height('40')
.backgroundColor('#ff1a73f8')
.borderRadius(20)
.textAlign(TextAlign.Center)
.margin({ left: 16, right: 16 })
.onClick(() => {
this.isVisible = Visibility.Visible; // 显示自定义组件
setTimeout(() => {
focusControl.requestFocus('textArea'); // 焦点切换到输入框
}, 10);
});
}.height('10%').width('100%');
}
.expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.BOTTOM]); // 适配键盘区域
// 遮罩层(点击隐藏自定义)
Column()
.width('100%')
.height('120%')
.opacity(0.5)
.backgroundColor('rgba(0,0,0,0.5)')
.onClick(() => {
this.isVisible = Visibility.Hidden; // 隐藏自定义组件
})
.visibility(this.isVisible)
.expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.BOTTOM, SafeAreaEdge.TOP]);
// 动态加载自定义组件
CommentComponent({ isVisible: this.isVisible, keyboardHeight: this.keyboardHeight });
};
}
// 页面卸载时隐藏自定义组件
aboutToDisappear(): void {
this.isVisible = Visibility.Hidden;
}
}
// 自定义工具栏组件
@Component
struct CommentComponent {
controller: RichEditorController = new RichEditorController();
@Link isVisible: Visibility;
@Link keyboardHeight: string;
build() {
Flex({ direction: FlexDirection.ColumnReverse, justifyContent: FlexAlign.Start, alignItems: ItemAlign.Stretch }) {
Row() {
RichEditor({ controller: this.controller })
.id('textArea') // 设置输入框ID用于焦点控制
.placeholder('喜欢就评论一下吧~', { fontColor: Color.Gray, font: { size: 16, weight: FontWeight.Normal } })
.width('65%');
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.End, alignItems: ItemAlign.Stretch }) {
Image($r('app.media.startIcon')).height(20).constraintSize({ minWidth: 20, maxWidth: 20 });
}
.width(110);
}
.margin({
top: 10,
bottom: this.keyboardHeight, // 根据键盘高度设置动态调整底部边距
left: 10,
right: 10
})
.border({ width: 1 })
.borderRadius(50);
}
.width('100%')
.height(380)
.expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.BOTTOM, SafeAreaEdge.TOP]) // 适配键盘区域
.backgroundColor(Color.White)
.visibility(this.isVisible);
}
}
https://pastebin.com/6KBPeVqL
https://pastebin.com/bN1ddiZp
https://pastebin.com/gtYW43NW
https://pastebin.com/eJcix7ad
https://pastebin.com/HcrRQFtA
https://pastebin.com/XgyPuxHD
https://pastebin.com/263D2tG3
https://pastebin.com/VFXnShya
https://pastebin.com/JcCfedC7
https://pastebin.com/XgiWLKtb
https://pastebin.com/SnA9AdtL
https://pastebin.com/gXXg0rwX
https://pastebin.com/6JGUtchA
https://pastebin.com/ZbTwd0Ua
https://pastebin.com/0s559jyS
https://pastebin.com/FF4bCbp7
https://pastebin.com/rbJciCS7
https://pastebin.com/fMBrbeYx
https://pastebin.com/3ZzHtZqE
https://pastebin.com/xgZc6Wpx
https://pastebin.com/q9MHz0sP
https://pastebin.com/7BGqgqgb
https://pastebin.com/762Emz0H
https://pastebin.com/KS7UgY63
https://pastebin.com/E0CUmHyN
https://pastebin.com/RaxmNbrv
https://pastebin.com/sWGhM2xB
https://pastebin.com/q4USiCDw
https://pastebin.com/XBjfa0Jv
https://pastebin.com/5R6CQqw3
https://pastebin.com/Q7C1fgyH
https://pastebin.com/fBtA7KM6
https://pastebin.com/dZHaQ1uQ
https://pastebin.com/YEKBNnfc
https://pastebin.com/T3fNdkNE
https://pastebin.com/r2YxuAHc
https://pastebin.com/Y1Fzshsu
https://pastebin.com/KJvxU2vN
https://pastebin.com/57egjdLv
https://pastebin.com/VxNKdCta
https://pastebin.com/3YsNKCSd
https://pastebin.com/Wk06JeP9
https://pastebin.com/T2pGjSNZ
https://pastebin.com/M0kVVxRE
https://pastebin.com/7kAYYh9u
https://pastebin.com/uiKRsuLh
https://pastebin.com/XLg7wEiV
https://pastebin.com/Uk7dPXfC
https://pastebin.com/HXaxi2bh
https://pastebin.com/2stztMET
https://pastebin.com/RxKisB4V
https://pastebin.com/ig8KqDGg
https://pastebin.com/cRQ0yb3J
https://pastebin.com/4hR7SdmD
https://pastebin.com/EwmMgWdr
https://pastebin.com/4b5AFeRk
https://pastebin.com/3CFxLac5
https://pastebin.com/mKn2fjXp
https://pastebin.com/BSa8L13Z
https://pastebin.com/NAtqrReY
https://pastebin.com/34KDinEG
https://pastebin.com/YaXZqyZQ
https://pastebin.com/j2MhC6kw
https://pastebin.com/c1n5dn5T
https://pastebin.com/weATT6j7
https://pastebin.com/zV5bp85z
https://pastebin.com/isfmyWk7
https://pastebin.com/S86UAeMg
https://pastebin.com/XkUgvZQW
https://pastebin.com/v9j6jg3T
https://pastebin.com/3ip0M9T8
https://pastebin.com/W9c1w8Xb
https://pastebin.com/jtcypgTt
https://pastebin.com/tgPhxe2L
https://pastebin.com/bs9jzpuL
https://pastebin.com/W8sLLPtk
https://pastebin.com/gJTGQYCL
https://pastebin.com/Qh2u2nkn
https://pastebin.com/EPEHmxwS
https://pastebin.com/y41haJUr
https://pastebin.com/J6cevDf0
https://pastebin.com/24RSFBR0
https://pastebin.com/KZsSaA18
https://pastebin.com/21egpH32
https://pastebin.com/wDziwJnn
https://pastebin.com/QeQvkA9r
https://pastebin.com/icJRn8VJ
https://pastebin.com/WsvP4LwZ
https://pastebin.com/H8nZikEJ
https://pastebin.com/rn2gyWiP
https://pastebin.com/tfehkve3
https://pastebin.com/kn7dX8Fh
https://pastebin.com/Dn1ZfNEV
https://pastebin.com/yy811Lis
https://pastebin.com/QcqL3CXH
https://pastebin.com/QbMe6xXP
https://pastebin.com/NpR2Ra0H
https://pastebin.com/DeevkS6j
https://pastebin.com/yhumdvyC
https://pastebin.com/mHjSzVib
https://pastebin.com/F2wyRKNJ
https://pastebin.com/cc96TLXV
https://pastebin.com/2U1qwTrS
https://pastebin.com/n6hYfTdQ
https://pastebin.com/rhAFXjq6
https://pastebin.com/Hmj59VVm
https://pastebin.com/YmrAxXMU
https://pastebin.com/JBF9n5PL
https://pastebin.com/f21MNNJt
https://pastebin.com/D1hn89Qa
https://pastebin.com/xqdaxD0A
https://pastebin.com/tm2zPQbn
https://pastebin.com/8j3PBMNW
https://pastebin.com/3LcqrmTu
https://pastebin.com/GY4abWzw
https://pastebin.com/9LnRRWuk
https://pastebin.com/N5HJByTK
https://pastebin.com/aaSvnC3j
https://pastebin.com/UYFUHSWk
https://pastebin.com/fcvPwAqU
https://pastebin.com/fS9cgSGG
https://pastebin.com/NP5mQWhJ
https://pastebin.com/em54RVwp
https://pastebin.com/FhSzXrRD
https://pastebin.com/EaU2AmjN
https://pastebin.com/86fScibj
https://pastebin.com/rgPcewwp
https://pastebin.com/FAhu2G96
https://pastebin.com/fU6un6pq
https://pastebin.com/Fmpvt6K9
https://pastebin.com/DMJHzHuW
https://pastebin.com/F39T4W12
https://pastebin.com/9wGgKwMC
https://pastebin.com/xJXUSDnS
https://pastebin.com/FqUGuWTV
https://pastebin.com/Z3ppjriB
https://pastebin.com/A2AQwvEd
https://pastebin.com/tqBWPMe7
https://pastebin.com/LQ3LFEHs
https://pastebin.com/qgkbKhDs
https://pastebin.com/vNvhLWpB
https://pastebin.com/BYu5Twtq
https://pastebin.com/9MapWu1K
https://pastebin.com/DUS2V33c
https://pastebin.com/WSuFmrmW
https://pastebin.com/vKwBpE8f
https://pastebin.com/ARLCtkJy
https://pastebin.com/R0eRbYXX
https://pastebin.com/vzusjTqP
https://pastebin.com/6xQWzuPp
https://pastebin.com/XZsLs6N3
https://pastebin.com/ccCGb1c1
https://pastebin.com/GbxBPVJ6
https://pastebin.com/c6rWM7yT
https://pastebin.com/0fhv7SWU
https://pastebin.com/LCXSxwqu
https://pastebin.com/UKiEaw1b
https://pastebin.com/rR7WFgRd
https://pastebin.com/GMr8Uit3
https://pastebin.com/EeUAEUzt
https://pastebin.com/iMdgtEvx
https://pastebin.com/M54w1AB8
https://pastebin.com/NBenUCdx
https://pastebin.com/gcYXCccc
https://pastebin.com/VKbbyQWT
https://pastebin.com/AjjbCsHT
https://pastebin.com/95MGXGGW
https://pastebin.com/MGSQGvHt
https://pastebin.com/8vVDgwEX
https://pastebin.com/xg8NhUUu
https://pastebin.com/ejAPdK9h
https://pastebin.com/HC44DqUE
https://pastebin.com/AAERa624
https://pastebin.com/TrqEhKJ0
https://pastebin.com/PhRqJLQH
https://pastebin.com/s10g8uCx
https://pastebin.com/a3RKhwkq
https://pastebin.com/PEsA2ngB
zero-markdown-view插件解析markdown问题修复
使用zero-markdown-view插件时解析的markdown,如果markdown中表格上面有一行文字就识别不到表格,示例如下
### 标题
从多维度对比差异:
| 表头1 | 表头2 | 表头3 |
|----------------|----------------------------|----------------------------|
| 1 | 2 | 3 |
只有将表格上空出一行才正常识别到表格,正常的如下:
### 标题
从多维度对比差异:
| 表头1 | 表头2 | 表头3 |
|----------------|----------------------------|----------------------------|
| 1 | 2 | 3 |
修复方法:
此插件依赖marked.min.js解析
- 将这个js文件下载下来https://cdn.jsdelivr.net/npm/marked@18.0.7/lib/marked.esm.js
- 将上面下载的js文件放到这个目录下/uni_modules/zero-markdown-view/components/mp-html/markdown/
- 打开这个文件/uni_modules/zero-markdown-view/components/mp-html/markdown/index.js
- 把第六行import marked from './marked.min'替换成import {marked} from './marked.esm'
这样就ok了
使用zero-markdown-view插件时解析的markdown,如果markdown中表格上面有一行文字就识别不到表格,示例如下
### 标题
从多维度对比差异:
| 表头1 | 表头2 | 表头3 |
|----------------|----------------------------|----------------------------|
| 1 | 2 | 3 |
只有将表格上空出一行才正常识别到表格,正常的如下:
### 标题
从多维度对比差异:
| 表头1 | 表头2 | 表头3 |
|----------------|----------------------------|----------------------------|
| 1 | 2 | 3 |
修复方法:
此插件依赖marked.min.js解析
- 将这个js文件下载下来https://cdn.jsdelivr.net/npm/marked@18.0.7/lib/marked.esm.js
- 将上面下载的js文件放到这个目录下/uni_modules/zero-markdown-view/components/mp-html/markdown/
- 打开这个文件/uni_modules/zero-markdown-view/components/mp-html/markdown/index.js
- 把第六行import marked from './marked.min'替换成import {marked} from './marked.esm'
这样就ok了
如何解决Repeat渲染数据重复显示问题
问题现象
使用Repeat实现列表功能,加载新数据会出现重复显示问题,一般有下面几种问题场景:
常见问题场景
问题描述
场景一
滑动加载新数据,在aboutToAppear方法里处理数据逻辑,导致数据重复。
场景二
Repeat与@Builder混用场景下,传参错误,导致数据重复。
场景一:滑动加载新数据,在aboutToAppear方法里处理数据逻辑,问题如图所示:
点击放大
场景二:进行Repeat与@Builder混用场景下,传参使用错误,导致数据重复,问题如图所示:
点击放大
背景知识
Repeat根据容器组件的有效加载范围(屏幕可视区域+预加载区域)加载子组件。当容器滑动/数组改变时,Repeat会根据父容器组件的布局过程重新计算有效加载范围,并管理列表子组件节点的创建与销毁。Repeat通过组件节点更新/复用从而优化性能表现。
节点更新复用能力说明:当滚动容器组件滑动/数组改变时,Repeat将失效的子组件节点(离开容器组件的显示区域和预加载区域)加入空闲节点缓存池中,即断开组件节点与页面组件树的连接但不销毁节点。在需要生成新的组件时,对缓存池里的组件节点进行复用。
aboutToAppear:aboutToAppear函数在创建自定义组件的新实例后,在执行其build()函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build()函数中生效。
问题定位
场景一:
根据问题代码分析,数据更新是在子组件的aboutToAppear方法里完成的,aboutToAppear在组件被创建时触发,之后不会再触发。因为Repeat提供了节点复用的能力,后续加载的是之前复用的节点,不会走aboutToAppear方法,导致数据没有更新。
问题代码如下:
@ComponentV2
struct LowCodeTitleView{
@Param ids: string = ''
@Local changes:string = ''
aboutToAppear(): void {
this.changes = this.ids // 数据更新是在子组件的aboutToAppear方法里完成的
}
build() {
Column(){
Text(this.changes+"标题内容")
}
}
}
@Entry
@ComponentV2
struct Index {
@Local dataArr: Array<string> = [];
aboutToAppear(): void {
for (let i = 0; i < 50; i++) {
this.dataArr.push(data_${i}); // 为数组添加一些数据
}
}
build() {
RelativeContainer() {
List({ space: 3 }) {
Repeat<string>(this.dataArr)
.each((ri: RepeatItem<string>) => {
ListItem() {
LowCodeTitleView({
ids:ri.item
})
}
})
.key((item: string, index: number): string => "__test_lowcode--"+index)
.virtualScroll({ totalCount: this.dataArr.length })
}.cachedCount(1)
}
.height('100%')
.width('100%')
}
}
场景二:
根据问题代码分析:
首页展示正常,说明节点创建操作正常。
当滚动容器组件滑动/数组改变时,Repeat将失效的子组件节点(离开有效加载范围)加入空闲节点缓存池中,即断开组件节点与页面组件树的连接但不销毁节点。在需要生成新的组件时,对缓存池里的组件节点进行复用。下滑后发现节点与历史出现的节点重复,说明节点复用时异常,推测传参的方式或类型不符合要求。
Repeat与Builder混用章节中描述:当Repeat与@Builder混用时,必须将RepeatItem类型整体进行传参,组件才能监听到数据变化,如果只传递RepeatItem.item或RepeatItem.index,将会出现UI渲染异常。
基于以上可确认问题原因在于组件imageItemView的传参有误。
问题代码如下:
List({ space: 10 }) {
Repeat<ItemDataV2>(this.imageList)
.each((ri: RepeatItem<ItemDataV2>) => {
ListItem() {
this.imageItemView(ri.item);
};
})
.key((item: ItemDataV2) => item.id.toString())
.templateId((item: ItemDataV2) => {
return item.type;
})
.virtualScroll({ totalCount: this.imageList.length });
}
分析结论
场景一:Repeat提供了节点复用的能力,节点复用的时候没有办法重走aboutToAppear,导致复用组件的数据没有及时刷新。需要把要更新的数据放在数据源里,通过数据源变化来触发Repeat刷新。
场景二:UI渲染异常根源在于Repeat与@Builder混用时传参错误,必须将RepeatItem类型整体进行传参而不是只传递RepeatItem.item或RepeatItem.index。
修改建议
场景一:
方案一:由于复用时aboutToAppear方法不会执行,无法在aboutToAppear里更新数据源,因此可以考虑通过Repeat直接监听数据源变化触发刷新,示例代码如下:
class Title {
id: number;
title: string;
constructor(id: number, title: string) {
this.id = id;
this.title = title;
}
}
@ComponentV2
struct LowCodeTitleView {
@Param title: Title = new Title(0, '标题内容'); // 数据从父组件传递给子组件,不走aboutToAppear
build() {
Column() {
Text(this.title.id + this.title.title);
}.margin({ left: 16, top: 10, bottom: 10 });
}
}
@Entry
@ComponentV2
struct RepeatLoadDataDemo {
@Local dataArr: Array<Title> = [];
aboutToAppear(): void {
for (let i = 0; i < 50; i++) {
this.dataArr.push(new Title(i, '标题内容')); // 为数组添加一些数据
}
}
build() {
RelativeContainer() {
List({ space: 3 }) {
Repeat<Title>(this.dataArr) // 把更新的数据放在数据源里
.each((ri: RepeatItem<Title>) => {
ListItem() {
LowCodeTitleView({
title: ri.item
});
};
})
.key((_item: Title, index: number): string => '__test_lowcode--' + index)
.virtualScroll({ totalCount: this.dataArr.length });
}.cachedCount(1).expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM]);
}.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
.height('100%')
.width('100%');
}
}
方案二:可以使用LazyForEach结合@Reusable实现列表组件的组件复用,在节点复用的时候使用aboutToReuse生命周期触发节点触发更新数据,参考链接示例代码:列表滚动配合LazyForEach使用。
在API 18后,Repeat提供了关闭自身复用的能力,详细参考:VirtualScrollOptions;配合@ReusableV2装饰的组件使用,复用的时候也可以触发组件的aboutToReuse生命周期函数。
场景二:
上述问题代码中this.imageItemView(ri.item)传参存在问题,必须将RepeatItem类型整体进行传参,应该改为this.imageItemView(ri)。
示例代码如下:
@ObservedV2
export class ItemDataV2 {
@Trace
id: number;
@Trace
type: string = '';
@Trace
title: ResourceStr;
@Trace
img: Resource;
constructor(id: number, title: ResourceStr, img: Resource, type?: string) {
this.id = id;
this.title = title;
this.img = img;
if (type) {
this.type = type;
}
}
}
@Entry
@ComponentV2
struct RepeatDemo {
@Local imageList: Array<ItemDataV2> = this.getFirstPageData();
// 模拟的第一页的数据
getFirstPageData(): Array<ItemDataV2> {
let imageList: Array<ItemDataV2> = [];
imageList.push(...getItemData(2, 10));
return imageList;
}
build() {
Column() {
Button('addItem').onClick(() => { // 点击按钮添加一页的数据
this.addTestData();
});
List({ space: 10 }) {
Repeat<ItemDataV2>(this.imageList)
.each((ri: RepeatItem<ItemDataV2>) => {
ListItem() {
this.imageItemView(ri);
};
})
.key((item: ItemDataV2) => item.id.toString())
.templateId((item: ItemDataV2) => {
return item.type;
})
.virtualScroll({ totalCount: this.imageList.length });
}.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
.cachedCount(6)
.width('100%')
.padding({
top: 15,
right: 15,
left: 15,
bottom: 12
});
}.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM]);
}
// 添加一页的数据
addTestData(): void {
let count = this.imageList.length;
let moreArr: ItemDataV2[] = getItemData(count, 10);
this.imageList.push(...moreArr);
}
@Builder
imageItemView(ri: RepeatItem<ItemDataV2>) {
Stack() {
Image(ri.item.img)
.objectFit(ImageFit.Cover)
.aspectRatio(3)
.borderRadius(12);
Text(ri.item.title)
.padding(15)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.fontColor(Color.Black);
}.alignContent(Alignment.TopStart)
.width('100%');
}
}
let swiperImg: Array<Resource> = [$r('app.media.backImage')]; // 背景图
// 创建模拟的数据
function getItemData(start: number, count: number): ItemDataV2[] {
let arr: ItemDataV2[] = [];
for (let i = 0; i < count; i++) {
let imageIndex = i % swiperImg.length;
arr.push(new ItemDataV2(i + start, (i + start).toString(), swiperImg[imageIndex]));
}
return arr;
}
https://pastebin.com/BMW3u7yk
https://pastebin.com/zr8N97Ne
https://pastebin.com/Gs298WgD
https://pastebin.com/FnxZDBcW
https://pastebin.com/i8rpfLEP
https://pastebin.com/ez7BZPE3
https://pastebin.com/U0KwnFSL
https://pastebin.com/R4cMh2SL
https://pastebin.com/676zm0WG
https://pastebin.com/H9pKi7w7
https://pastebin.com/dbtzJw0x
https://pastebin.com/QLWvWbqU
https://pastebin.com/yGPiJTZD
https://pastebin.com/7VminAc3
https://pastebin.com/rsScjjFE
https://pastebin.com/ez8zq4VT
https://pastebin.com/1efA7vcf
https://pastebin.com/1HpF960z
https://pastebin.com/DLn96YHA
https://pastebin.com/8dFFy65M
https://pastebin.com/TKEbGuxn
https://pastebin.com/FVgewR7x
https://pastebin.com/XTKjPrmz
https://pastebin.com/CjtL2CbZ
https://pastebin.com/8JsJ7bMj
https://pastebin.com/a9RikA98
https://pastebin.com/DBn55k14
https://pastebin.com/fNpm9vYB
https://pastebin.com/72ZfQ149
https://pastebin.com/i7N5Avqf
https://pastebin.com/GUXF7KDm
https://pastebin.com/Ku19TS4j
https://pastebin.com/sqttnjrA
https://pastebin.com/9BVvdDdC
https://pastebin.com/CHYZ1Gvb
https://pastebin.com/hrbjEy3W
https://pastebin.com/Eejnahjn
https://pastebin.com/BJjGW58r
https://pastebin.com/TA5zPz46
https://pastebin.com/aWz5V4yR
https://pastebin.com/gLqvHV7C
https://pastebin.com/zrFtuaUg
https://pastebin.com/225KFvYC
https://pastebin.com/hYe0TumF
https://pastebin.com/KE2Ux8wJ
https://pastebin.com/TMdN3eBf
https://pastebin.com/JACkCBXg
https://pastebin.com/uQEujZg0
https://pastebin.com/aqgRAuwQ
https://pastebin.com/jpxU5vmQ
https://pastebin.com/Zhmfn6xS
https://pastebin.com/gLz2BJup
https://pastebin.com/qwWaQzjV
https://pastebin.com/dsc3dh7Q
https://pastebin.com/MEeAfNrK
https://pastebin.com/s13exYvP
https://pastebin.com/BGw364Z8
https://pastebin.com/cJKMevm3
https://pastebin.com/6DDggPWC
https://pastebin.com/UpDpAga4
https://pastebin.com/Lw1s28nY
https://pastebin.com/tLM0z9LE
https://pastebin.com/bVVHFj6b
https://pastebin.com/FunGXsh7
https://pastebin.com/ChnzMQ8K
https://pastebin.com/TLQiKJqr
https://pastebin.com/3jiBF2qM
https://pastebin.com/bXUHz9bE
https://pastebin.com/L3MVPMQq
https://pastebin.com/WYWQGEQV
https://pastebin.com/qB8KP2UN
https://pastebin.com/sf84cdKm
https://pastebin.com/1hmh7csp
https://pastebin.com/ZdW6ZsCP
https://pastebin.com/83GH1cLG
https://pastebin.com/dVp5TAsp
https://pastebin.com/D9MPcZSw
https://pastebin.com/dyUNcKUb
https://pastebin.com/GVGM2jKa
https://pastebin.com/ttCQv2jU
https://pastebin.com/U2hAp61K
https://pastebin.com/uX8yxjv3
https://pastebin.com/SE3Yq25k
https://pastebin.com/NkvV232B
https://pastebin.com/SGPc5xik
https://pastebin.com/fBmMd2cN
https://pastebin.com/9wsVURDP
https://pastebin.com/y4TmwfYR
https://pastebin.com/JcTuRYrc
https://pastebin.com/V8RPz7mM
https://pastebin.com/YqASCN8G
https://pastebin.com/6JMnz3jC
https://pastebin.com/JKN9bkBR
https://pastebin.com/YkX3cz9S
https://pastebin.com/L71qyZBH
https://pastebin.com/af14FyAF
https://pastebin.com/rYKWY5hk
https://pastebin.com/bcHNKC0q
https://pastebin.com/avy1Qyra
https://pastebin.com/v08NsSpW
https://pastebin.com/bxPJwdh2
https://pastebin.com/vV3Lxu9E
https://pastebin.com/PMwyJDrr
https://pastebin.com/GNceZj3i
https://pastebin.com/QAgS2DBq
https://pastebin.com/xU0LsnLd
https://pastebin.com/QaNHe5E3
https://pastebin.com/qxtNYsxX
https://pastebin.com/ApPBs6pZ
https://pastebin.com/W2N66ehs
https://pastebin.com/7QVU487N
https://pastebin.com/NK2wvLaE
https://pastebin.com/LxeFEpZ5
https://pastebin.com/0RnYrav7
https://pastebin.com/EYw7h4gC
https://pastebin.com/7yqhn05R
https://pastebin.com/Pkhb5WGT
https://pastebin.com/dcF8cERK
https://pastebin.com/WSitbd4k
https://pastebin.com/VJkwygDS
https://pastebin.com/AWqu7HfY
https://pastebin.com/dpSAXydY
https://pastebin.com/QRC4ygGj
https://pastebin.com/2E991jhR
https://pastebin.com/349smxri
https://pastebin.com/d8LJ0Q6C
https://pastebin.com/KYmcfhUq
https://pastebin.com/NYF6CT4C
https://pastebin.com/Fa6XQ06R
https://pastebin.com/DRe4gE72
https://pastebin.com/NvzHJugB
https://pastebin.com/bpYrBJ9Q
https://pastebin.com/AnC8XMWr
https://pastebin.com/1c2sjpwh
https://pastebin.com/yhXGhB8E
https://pastebin.com/itRM2ZMd
https://pastebin.com/aR9HpTRH
https://pastebin.com/m19RYG7j
https://pastebin.com/xjpU9ksH
https://pastebin.com/xiN4JaXB
https://pastebin.com/1gU4EArR
https://pastebin.com/6qhtwYk1
https://pastebin.com/H64fri79
https://pastebin.com/xsRKbG1m
https://pastebin.com/UipZaKhK
https://pastebin.com/RAbT0kVq
https://pastebin.com/0i00ADZz
https://pastebin.com/iurUhSyk
https://pastebin.com/AJ90NhRk
https://pastebin.com/rsyZZcM5
https://pastebin.com/fST61sHE
https://pastebin.com/tnxRKNzD
https://pastebin.com/dk9KKKDm
https://pastebin.com/gqwbsWku
https://pastebin.com/uxSXWcdC
https://pastebin.com/T59UHk0f
https://pastebin.com/058HRADt
https://pastebin.com/Qa8MpNXB
https://pastebin.com/W5KVa6Bu
https://pastebin.com/gJUwCVjy
https://pastebin.com/86avgWTq
https://pastebin.com/w8JAu1sb
https://pastebin.com/LbUD3yhy
https://pastebin.com/RAWTZN9P
https://pastebin.com/ivG5UTZ1
https://pastebin.com/vU366iR6
https://pastebin.com/XCA86ssH
https://pastebin.com/YgKSxnVv
https://pastebin.com/B6suLGgy
https://pastebin.com/vxZ0nFqR
https://pastebin.com/DZ0nxixL
https://pastebin.com/PqdR7bxv
https://pastebin.com/RmZa7vqb
https://pastebin.com/EhUSwQ4z
https://pastebin.com/9pHd3GTL
https://pastebin.com/VfF8FGVe
https://pastebin.com/T66RxLCX
https://pastebin.com/7fCyXFKW
https://pastebin.com/vcrXHYSx
https://pastebin.com/bj4mJD6y
https://pastebin.com/5rgDxsgD
https://pastebin.com/T0pMab3R
https://pastebin.com/G5LQvwML
https://pastebin.com/tvyGHmzU
https://pastebin.com/ax9M09Mi
https://pastebin.com/8ZduUtUd
https://pastebin.com/9490Ajrb
https://pastebin.com/2VLuQDwG
https://pastebin.com/tt4yG2tw
https://pastebin.com/zJmwjhrr
https://pastebin.com/dbde4zgM
https://pastebin.com/QFkQaF3K
https://pastebin.com/V3S6HFfw
https://pastebin.com/zuip5PZw
https://pastebin.com/rfSqfzE4
https://pastebin.com/LRWRUJcA
https://pastebin.com/1Dz9d3J6
https://pastebin.com/QNRn2bjK
问题现象
使用Repeat实现列表功能,加载新数据会出现重复显示问题,一般有下面几种问题场景:
常见问题场景
问题描述
场景一
滑动加载新数据,在aboutToAppear方法里处理数据逻辑,导致数据重复。
场景二
Repeat与@Builder混用场景下,传参错误,导致数据重复。
场景一:滑动加载新数据,在aboutToAppear方法里处理数据逻辑,问题如图所示:
点击放大
场景二:进行Repeat与@Builder混用场景下,传参使用错误,导致数据重复,问题如图所示:
点击放大
背景知识
Repeat根据容器组件的有效加载范围(屏幕可视区域+预加载区域)加载子组件。当容器滑动/数组改变时,Repeat会根据父容器组件的布局过程重新计算有效加载范围,并管理列表子组件节点的创建与销毁。Repeat通过组件节点更新/复用从而优化性能表现。
节点更新复用能力说明:当滚动容器组件滑动/数组改变时,Repeat将失效的子组件节点(离开容器组件的显示区域和预加载区域)加入空闲节点缓存池中,即断开组件节点与页面组件树的连接但不销毁节点。在需要生成新的组件时,对缓存池里的组件节点进行复用。
aboutToAppear:aboutToAppear函数在创建自定义组件的新实例后,在执行其build()函数之前执行。允许在aboutToAppear函数中改变状态变量,更改将在后续执行build()函数中生效。
问题定位
场景一:
根据问题代码分析,数据更新是在子组件的aboutToAppear方法里完成的,aboutToAppear在组件被创建时触发,之后不会再触发。因为Repeat提供了节点复用的能力,后续加载的是之前复用的节点,不会走aboutToAppear方法,导致数据没有更新。
问题代码如下:
@ComponentV2
struct LowCodeTitleView{
@Param ids: string = ''
@Local changes:string = ''
aboutToAppear(): void {
this.changes = this.ids // 数据更新是在子组件的aboutToAppear方法里完成的
}
build() {
Column(){
Text(this.changes+"标题内容")
}
}
}
@Entry
@ComponentV2
struct Index {
@Local dataArr: Array<string> = [];
aboutToAppear(): void {
for (let i = 0; i < 50; i++) {
this.dataArr.push(data_${i}); // 为数组添加一些数据
}
}
build() {
RelativeContainer() {
List({ space: 3 }) {
Repeat<string>(this.dataArr)
.each((ri: RepeatItem<string>) => {
ListItem() {
LowCodeTitleView({
ids:ri.item
})
}
})
.key((item: string, index: number): string => "__test_lowcode--"+index)
.virtualScroll({ totalCount: this.dataArr.length })
}.cachedCount(1)
}
.height('100%')
.width('100%')
}
}
场景二:
根据问题代码分析:
首页展示正常,说明节点创建操作正常。
当滚动容器组件滑动/数组改变时,Repeat将失效的子组件节点(离开有效加载范围)加入空闲节点缓存池中,即断开组件节点与页面组件树的连接但不销毁节点。在需要生成新的组件时,对缓存池里的组件节点进行复用。下滑后发现节点与历史出现的节点重复,说明节点复用时异常,推测传参的方式或类型不符合要求。
Repeat与Builder混用章节中描述:当Repeat与@Builder混用时,必须将RepeatItem类型整体进行传参,组件才能监听到数据变化,如果只传递RepeatItem.item或RepeatItem.index,将会出现UI渲染异常。
基于以上可确认问题原因在于组件imageItemView的传参有误。
问题代码如下:
List({ space: 10 }) {
Repeat<ItemDataV2>(this.imageList)
.each((ri: RepeatItem<ItemDataV2>) => {
ListItem() {
this.imageItemView(ri.item);
};
})
.key((item: ItemDataV2) => item.id.toString())
.templateId((item: ItemDataV2) => {
return item.type;
})
.virtualScroll({ totalCount: this.imageList.length });
}
分析结论
场景一:Repeat提供了节点复用的能力,节点复用的时候没有办法重走aboutToAppear,导致复用组件的数据没有及时刷新。需要把要更新的数据放在数据源里,通过数据源变化来触发Repeat刷新。
场景二:UI渲染异常根源在于Repeat与@Builder混用时传参错误,必须将RepeatItem类型整体进行传参而不是只传递RepeatItem.item或RepeatItem.index。
修改建议
场景一:
方案一:由于复用时aboutToAppear方法不会执行,无法在aboutToAppear里更新数据源,因此可以考虑通过Repeat直接监听数据源变化触发刷新,示例代码如下:
class Title {
id: number;
title: string;
constructor(id: number, title: string) {
this.id = id;
this.title = title;
}
}
@ComponentV2
struct LowCodeTitleView {
@Param title: Title = new Title(0, '标题内容'); // 数据从父组件传递给子组件,不走aboutToAppear
build() {
Column() {
Text(this.title.id + this.title.title);
}.margin({ left: 16, top: 10, bottom: 10 });
}
}
@Entry
@ComponentV2
struct RepeatLoadDataDemo {
@Local dataArr: Array<Title> = [];
aboutToAppear(): void {
for (let i = 0; i < 50; i++) {
this.dataArr.push(new Title(i, '标题内容')); // 为数组添加一些数据
}
}
build() {
RelativeContainer() {
List({ space: 3 }) {
Repeat<Title>(this.dataArr) // 把更新的数据放在数据源里
.each((ri: RepeatItem<Title>) => {
ListItem() {
LowCodeTitleView({
title: ri.item
});
};
})
.key((_item: Title, index: number): string => '__test_lowcode--' + index)
.virtualScroll({ totalCount: this.dataArr.length });
}.cachedCount(1).expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM]);
}.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
.height('100%')
.width('100%');
}
}
方案二:可以使用LazyForEach结合@Reusable实现列表组件的组件复用,在节点复用的时候使用aboutToReuse生命周期触发节点触发更新数据,参考链接示例代码:列表滚动配合LazyForEach使用。
在API 18后,Repeat提供了关闭自身复用的能力,详细参考:VirtualScrollOptions;配合@ReusableV2装饰的组件使用,复用的时候也可以触发组件的aboutToReuse生命周期函数。
场景二:
上述问题代码中this.imageItemView(ri.item)传参存在问题,必须将RepeatItem类型整体进行传参,应该改为this.imageItemView(ri)。
示例代码如下:
@ObservedV2
export class ItemDataV2 {
@Trace
id: number;
@Trace
type: string = '';
@Trace
title: ResourceStr;
@Trace
img: Resource;
constructor(id: number, title: ResourceStr, img: Resource, type?: string) {
this.id = id;
this.title = title;
this.img = img;
if (type) {
this.type = type;
}
}
}
@Entry
@ComponentV2
struct RepeatDemo {
@Local imageList: Array<ItemDataV2> = this.getFirstPageData();
// 模拟的第一页的数据
getFirstPageData(): Array<ItemDataV2> {
let imageList: Array<ItemDataV2> = [];
imageList.push(...getItemData(2, 10));
return imageList;
}
build() {
Column() {
Button('addItem').onClick(() => { // 点击按钮添加一页的数据
this.addTestData();
});
List({ space: 10 }) {
Repeat<ItemDataV2>(this.imageList)
.each((ri: RepeatItem<ItemDataV2>) => {
ListItem() {
this.imageItemView(ri);
};
})
.key((item: ItemDataV2) => item.id.toString())
.templateId((item: ItemDataV2) => {
return item.type;
})
.virtualScroll({ totalCount: this.imageList.length });
}.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
.cachedCount(6)
.width('100%')
.padding({
top: 15,
right: 15,
left: 15,
bottom: 12
});
}.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM]);
}
// 添加一页的数据
addTestData(): void {
let count = this.imageList.length;
let moreArr: ItemDataV2[] = getItemData(count, 10);
this.imageList.push(...moreArr);
}
@Builder
imageItemView(ri: RepeatItem<ItemDataV2>) {
Stack() {
Image(ri.item.img)
.objectFit(ImageFit.Cover)
.aspectRatio(3)
.borderRadius(12);
Text(ri.item.title)
.padding(15)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.fontColor(Color.Black);
}.alignContent(Alignment.TopStart)
.width('100%');
}
}
let swiperImg: Array<Resource> = [$r('app.media.backImage')]; // 背景图
// 创建模拟的数据
function getItemData(start: number, count: number): ItemDataV2[] {
let arr: ItemDataV2[] = [];
for (let i = 0; i < count; i++) {
let imageIndex = i % swiperImg.length;
arr.push(new ItemDataV2(i + start, (i + start).toString(), swiperImg[imageIndex]));
}
return arr;
}
https://pastebin.com/BMW3u7yk
https://pastebin.com/zr8N97Ne
https://pastebin.com/Gs298WgD
https://pastebin.com/FnxZDBcW
https://pastebin.com/i8rpfLEP
https://pastebin.com/ez7BZPE3
https://pastebin.com/U0KwnFSL
https://pastebin.com/R4cMh2SL
https://pastebin.com/676zm0WG
https://pastebin.com/H9pKi7w7
https://pastebin.com/dbtzJw0x
https://pastebin.com/QLWvWbqU
https://pastebin.com/yGPiJTZD
https://pastebin.com/7VminAc3
https://pastebin.com/rsScjjFE
https://pastebin.com/ez8zq4VT
https://pastebin.com/1efA7vcf
https://pastebin.com/1HpF960z
https://pastebin.com/DLn96YHA
https://pastebin.com/8dFFy65M
https://pastebin.com/TKEbGuxn
https://pastebin.com/FVgewR7x
https://pastebin.com/XTKjPrmz
https://pastebin.com/CjtL2CbZ
https://pastebin.com/8JsJ7bMj
https://pastebin.com/a9RikA98
https://pastebin.com/DBn55k14
https://pastebin.com/fNpm9vYB
https://pastebin.com/72ZfQ149
https://pastebin.com/i7N5Avqf
https://pastebin.com/GUXF7KDm
https://pastebin.com/Ku19TS4j
https://pastebin.com/sqttnjrA
https://pastebin.com/9BVvdDdC
https://pastebin.com/CHYZ1Gvb
https://pastebin.com/hrbjEy3W
https://pastebin.com/Eejnahjn
https://pastebin.com/BJjGW58r
https://pastebin.com/TA5zPz46
https://pastebin.com/aWz5V4yR
https://pastebin.com/gLqvHV7C
https://pastebin.com/zrFtuaUg
https://pastebin.com/225KFvYC
https://pastebin.com/hYe0TumF
https://pastebin.com/KE2Ux8wJ
https://pastebin.com/TMdN3eBf
https://pastebin.com/JACkCBXg
https://pastebin.com/uQEujZg0
https://pastebin.com/aqgRAuwQ
https://pastebin.com/jpxU5vmQ
https://pastebin.com/Zhmfn6xS
https://pastebin.com/gLz2BJup
https://pastebin.com/qwWaQzjV
https://pastebin.com/dsc3dh7Q
https://pastebin.com/MEeAfNrK
https://pastebin.com/s13exYvP
https://pastebin.com/BGw364Z8
https://pastebin.com/cJKMevm3
https://pastebin.com/6DDggPWC
https://pastebin.com/UpDpAga4
https://pastebin.com/Lw1s28nY
https://pastebin.com/tLM0z9LE
https://pastebin.com/bVVHFj6b
https://pastebin.com/FunGXsh7
https://pastebin.com/ChnzMQ8K
https://pastebin.com/TLQiKJqr
https://pastebin.com/3jiBF2qM
https://pastebin.com/bXUHz9bE
https://pastebin.com/L3MVPMQq
https://pastebin.com/WYWQGEQV
https://pastebin.com/qB8KP2UN
https://pastebin.com/sf84cdKm
https://pastebin.com/1hmh7csp
https://pastebin.com/ZdW6ZsCP
https://pastebin.com/83GH1cLG
https://pastebin.com/dVp5TAsp
https://pastebin.com/D9MPcZSw
https://pastebin.com/dyUNcKUb
https://pastebin.com/GVGM2jKa
https://pastebin.com/ttCQv2jU
https://pastebin.com/U2hAp61K
https://pastebin.com/uX8yxjv3
https://pastebin.com/SE3Yq25k
https://pastebin.com/NkvV232B
https://pastebin.com/SGPc5xik
https://pastebin.com/fBmMd2cN
https://pastebin.com/9wsVURDP
https://pastebin.com/y4TmwfYR
https://pastebin.com/JcTuRYrc
https://pastebin.com/V8RPz7mM
https://pastebin.com/YqASCN8G
https://pastebin.com/6JMnz3jC
https://pastebin.com/JKN9bkBR
https://pastebin.com/YkX3cz9S
https://pastebin.com/L71qyZBH
https://pastebin.com/af14FyAF
https://pastebin.com/rYKWY5hk
https://pastebin.com/bcHNKC0q
https://pastebin.com/avy1Qyra
https://pastebin.com/v08NsSpW
https://pastebin.com/bxPJwdh2
https://pastebin.com/vV3Lxu9E
https://pastebin.com/PMwyJDrr
https://pastebin.com/GNceZj3i
https://pastebin.com/QAgS2DBq
https://pastebin.com/xU0LsnLd
https://pastebin.com/QaNHe5E3
https://pastebin.com/qxtNYsxX
https://pastebin.com/ApPBs6pZ
https://pastebin.com/W2N66ehs
https://pastebin.com/7QVU487N
https://pastebin.com/NK2wvLaE
https://pastebin.com/LxeFEpZ5
https://pastebin.com/0RnYrav7
https://pastebin.com/EYw7h4gC
https://pastebin.com/7yqhn05R
https://pastebin.com/Pkhb5WGT
https://pastebin.com/dcF8cERK
https://pastebin.com/WSitbd4k
https://pastebin.com/VJkwygDS
https://pastebin.com/AWqu7HfY
https://pastebin.com/dpSAXydY
https://pastebin.com/QRC4ygGj
https://pastebin.com/2E991jhR
https://pastebin.com/349smxri
https://pastebin.com/d8LJ0Q6C
https://pastebin.com/KYmcfhUq
https://pastebin.com/NYF6CT4C
https://pastebin.com/Fa6XQ06R
https://pastebin.com/DRe4gE72
https://pastebin.com/NvzHJugB
https://pastebin.com/bpYrBJ9Q
https://pastebin.com/AnC8XMWr
https://pastebin.com/1c2sjpwh
https://pastebin.com/yhXGhB8E
https://pastebin.com/itRM2ZMd
https://pastebin.com/aR9HpTRH
https://pastebin.com/m19RYG7j
https://pastebin.com/xjpU9ksH
https://pastebin.com/xiN4JaXB
https://pastebin.com/1gU4EArR
https://pastebin.com/6qhtwYk1
https://pastebin.com/H64fri79
https://pastebin.com/xsRKbG1m
https://pastebin.com/UipZaKhK
https://pastebin.com/RAbT0kVq
https://pastebin.com/0i00ADZz
https://pastebin.com/iurUhSyk
https://pastebin.com/AJ90NhRk
https://pastebin.com/rsyZZcM5
https://pastebin.com/fST61sHE
https://pastebin.com/tnxRKNzD
https://pastebin.com/dk9KKKDm
https://pastebin.com/gqwbsWku
https://pastebin.com/uxSXWcdC
https://pastebin.com/T59UHk0f
https://pastebin.com/058HRADt
https://pastebin.com/Qa8MpNXB
https://pastebin.com/W5KVa6Bu
https://pastebin.com/gJUwCVjy
https://pastebin.com/86avgWTq
https://pastebin.com/w8JAu1sb
https://pastebin.com/LbUD3yhy
https://pastebin.com/RAWTZN9P
https://pastebin.com/ivG5UTZ1
https://pastebin.com/vU366iR6
https://pastebin.com/XCA86ssH
https://pastebin.com/YgKSxnVv
https://pastebin.com/B6suLGgy
https://pastebin.com/vxZ0nFqR
https://pastebin.com/DZ0nxixL
https://pastebin.com/PqdR7bxv
https://pastebin.com/RmZa7vqb
https://pastebin.com/EhUSwQ4z
https://pastebin.com/9pHd3GTL
https://pastebin.com/VfF8FGVe
https://pastebin.com/T66RxLCX
https://pastebin.com/7fCyXFKW
https://pastebin.com/vcrXHYSx
https://pastebin.com/bj4mJD6y
https://pastebin.com/5rgDxsgD
https://pastebin.com/T0pMab3R
https://pastebin.com/G5LQvwML
https://pastebin.com/tvyGHmzU
https://pastebin.com/ax9M09Mi
https://pastebin.com/8ZduUtUd
https://pastebin.com/9490Ajrb
https://pastebin.com/2VLuQDwG
https://pastebin.com/tt4yG2tw
https://pastebin.com/zJmwjhrr
https://pastebin.com/dbde4zgM
https://pastebin.com/QFkQaF3K
https://pastebin.com/V3S6HFfw
https://pastebin.com/zuip5PZw
https://pastebin.com/rfSqfzE4
https://pastebin.com/LRWRUJcA
https://pastebin.com/1Dz9d3J6
https://pastebin.com/QNRn2bjK
最近用 Cursor 写了个 uniapp 小程序,发现 AI 生成的代码比我自己写的更懂页面性能
用 Cursor 优化 uniapp 列表页:虚拟列表与按需更新实践
我为什么开始用 AI 写小程序
先说说我的处境。我在一个小团队做前端,主要用 uniapp + Vue 2 写小程序。之前我一直觉得 AI 写代码就是个玩具,顶多写写 demo 或者补注释,真要上生产还得靠人工调优。但上个月接了个社区团购小程序——商品列表、购物车、订单管理,还要实时显示库存,需求方要求 10 天上线,团队只有两个人。时间紧得我只能硬着头皮试 Cursor。
原本我打算让 AI 把基础页面和 API 对接写完,我自己再改性能问题。结果发现,AI 在我完全没想到的地方自动做了优化,甚至比我手写的代码更清楚小程序页面的性能瓶颈在哪里。
我写的列表页为什么卡?
先自曝一下我的老问题。以前写 uniapp 商品列表页,我习惯用 v-for 直接渲染全部数据,配合 onReachBottom 做分页加载。逻辑很简单:页面加载时请求第一页,滚到底部时请求下一页,新数据 concat 到原数组。列表项里每个商品都带图片、价格、标签、库存状态。
这种写法在小数据量(几十条)时没问题,但列表项超过 200 条就开始卡,尤其低端安卓机上滑动时掉帧明显。我之前的优化手段就是加个 v-if 控制图片懒加载,或者用 wx:if 代替 v-show,效果有限。
用 Cursor 时,我给的提示词很简单:“用 uniapp 写一个商品列表页,支持分页加载,列表项包含图片、价格和库存,注意性能。”它输出的代码让我有点意外,因为它自动做了几件我在写类似页面时根本没想到的事:
- 用 virtual-list 组件代替了 scroll-view + v-for。
- 对图片做了预加载和内存回收。
- 对库存状态变化做了按需更新,而不是整个列表重新渲染。
三个被 AI 提醒的优化细节
- 虚拟列表:不是所有数据都要渲染
AI 生成的代码直接用了 uniapp 的 uni-virtual-list 组件。这个组件我之前知道,但总觉得配置复杂,担心兼容性问题,一直没敢用。AI 却毫不犹豫地用了,而且配置得很干净。
核心思路是只渲染当前可见区域内的列表项,超出视口的 dom 节点被回收。比如一个 500 条数据的列表,实际 dom 节点可能只有 20 个。这直接解决了滑动卡顿的问题。
AI 生成的代码大致长这样(我做了简化):
javascript
{{ item.name }}
{{ item.price }}
而我之前手动写的是嵌套在 scroll-view 里的 v-for。两者性能差距在真机上非常明显:同样 300 条数据,用虚拟列表的页面滑动帧率稳定在 55fps 以上,而我的老写法在低端机上只有 20fps 左右。
坑点注意:uni-virtual-list 要求列表项高度固定,否则会计算错位。如果你的列表项高度不固定(比如有的商品描述文字多、有的少),需要提前做高度估算,或者用 item-key 配合动态高度。AI 在这里没处理动态高度,我是后来手动加了个 setTimeout 重新计算高度才解决的。
- 图片懒加载 + 内存回收:AI 自动加了“垃圾回收”
另一个让我惊讶的点是,AI 在图片加载上做了两层优化:
- 第一层:用 lazy-load 属性,让图片只在进入视口时才加载。
- 第二层:在 onUnload 生命周期里,手动清理图片缓存。
第二层优化我从来没想到过。小程序不像浏览器,它的内存管理很保守,大量图片加载后如果不释放,会导致页面越来越卡。AI 生成的代码里,这样写:
javascript
onUnload() {
this.goodsList.forEach(item => {
if (item.thumb) {
uni.downloadFile({ url: item.thumb, success: (res) => {
// 这里其实应该用 wx.cleanFileCache 之类的方法
// 但 AI 写的是手动释放内存,我改成了调用 SDK 方法
}})
}
})
}
虽然这个写法不够严谨(uni.downloadFile 不负责清理),但它提醒了我一个方向。后来我改成了调用 uni.getSavedFileList 和 uni.removeSavedFile 来清理临时文件。这个优化在用户频繁切换页面时效果很明显,页面回退后不会因为缓存堆积而卡顿。
我踩的坑:AI 生成的代码里,onUnload 中直接循环清理,但如果列表很大(比如 1000 条),这个操作本身就会卡住页面。我后来加了个 nextTick 和分批清理的逻辑,类似这样:
javascript
let batchSize = 50
for (let i = 0; i {
this.goodsList.slice(i, i + batchSize).forEach(...)
}, 0)
}
- 按需更新库存:避免整个列表重渲染
我们项目的库存是实时变化的,用户下单后,其他用户的页面上库存数字要立刻更新。以前我的做法是:收到 WebSocket 推送后,重新请求整个列表数据,然后覆盖 goodsList。这会导致整个列表重新渲染,即使只改了一个商品的库存。
AI 生成的代码里,它用了一个很巧妙的方案:维护一个 stockMap 对象,键是商品 ID,值是库存数量。列表渲染时,直接从 stockMap 读取库存,而不是从商品数据里取。更新时只更新 stockMap 中对应 ID 的值,不触发整个列表的 setData。
代码思路:
javascript
data() {
return {
goodsList: [],
stockMap: {} // { goodsId: stock }
}
},
methods: {
updateStock(goodsId, newStock) {
this.stockMap[goodsId] = newStock
// 只更新 stockMap,不重新设置 goodsList
this.$forceUpdate() // 或者用 Vue.set
}
}
虽然 $forceUpdate 仍然会触发一些组件更新,但比重新设置整个 goodsList 要轻量得多。而且 AI 在模板里用 stockMap[item.id] 而不是 item.stock,这一点我手动改代码时经常忽略。
代价:这个方案会增加内存开销,因为多维护了一个 stockMap 对象。但相比性能提升,这点内存完全可以接受。如果你的列表项超过 10000 条,可以考虑用 Map 代替普通对象,或者用 WeakMap 做自动回收。
AI 不是万能的,需要人工“兜底”
虽然 Cursor 帮我写了不少好代码,但我也发现了一些需要人工处理的问题:
-
虚拟列表的滚动事件兼容性:uni-virtual-list 在 iOS 上偶尔会出现滚动位置偏移,AI 没处理。我手动加了一个 @scroll 事件监听,用 scrollTop 做二次校准。
-
图片懒加载的占位图:AI 生成的代码没给 image 加 placeholder 属性,导致图片加载前显示空白,用户体验不好。我手动加了 @error 和 @load 事件来处理加载失败和成功。
-
库存更新的并发问题:如果 WebSocket 推送太快(比如秒杀场景),stockMap 的更新可能会覆盖。我加了一个队列机制,保证每次更新都是基于最新值。
-
代码可读性:AI 生成的代码虽然高效,但变量命名很随意(比如 item、temp、arr)。如果不重命名,团队协作时别人看不懂。我花了半小时把变量名改成有业务含义的。
总结:AI 帮我打开了性能优化的新视角
这次用 Cursor 写 uniapp 小程序的经历,让我意识到两件事:
- 第一,AI 在性能优化上的“直觉”比很多开发者都强,因为它训练的数据里包含了大量真实项目的性能优化模式,而这些模式我们平时很少主动学习。
- 第二,AI 不能替代开发者的判断力,但可以作为一个“性能顾问”,帮你指出那些你根本没想到的优化点。
如果你也在用 uniapp 做小程序,强烈建议试试让 AI 帮你生成列表页、详情页这类高频渲染的页面。但记得,AI 输出的代码要逐行审查,尤其是边界条件和内存管理。毕竟,最懂你业务逻辑的,还是你自己。
最后,如果你也在用 Cursor 或者 Copilot 写 uniapp,欢迎在评论区分享你遇到的坑和优化技巧。
用 Cursor 优化 uniapp 列表页:虚拟列表与按需更新实践
我为什么开始用 AI 写小程序
先说说我的处境。我在一个小团队做前端,主要用 uniapp + Vue 2 写小程序。之前我一直觉得 AI 写代码就是个玩具,顶多写写 demo 或者补注释,真要上生产还得靠人工调优。但上个月接了个社区团购小程序——商品列表、购物车、订单管理,还要实时显示库存,需求方要求 10 天上线,团队只有两个人。时间紧得我只能硬着头皮试 Cursor。
原本我打算让 AI 把基础页面和 API 对接写完,我自己再改性能问题。结果发现,AI 在我完全没想到的地方自动做了优化,甚至比我手写的代码更清楚小程序页面的性能瓶颈在哪里。
我写的列表页为什么卡?
先自曝一下我的老问题。以前写 uniapp 商品列表页,我习惯用 v-for 直接渲染全部数据,配合 onReachBottom 做分页加载。逻辑很简单:页面加载时请求第一页,滚到底部时请求下一页,新数据 concat 到原数组。列表项里每个商品都带图片、价格、标签、库存状态。
这种写法在小数据量(几十条)时没问题,但列表项超过 200 条就开始卡,尤其低端安卓机上滑动时掉帧明显。我之前的优化手段就是加个 v-if 控制图片懒加载,或者用 wx:if 代替 v-show,效果有限。
用 Cursor 时,我给的提示词很简单:“用 uniapp 写一个商品列表页,支持分页加载,列表项包含图片、价格和库存,注意性能。”它输出的代码让我有点意外,因为它自动做了几件我在写类似页面时根本没想到的事:
- 用 virtual-list 组件代替了 scroll-view + v-for。
- 对图片做了预加载和内存回收。
- 对库存状态变化做了按需更新,而不是整个列表重新渲染。
三个被 AI 提醒的优化细节
- 虚拟列表:不是所有数据都要渲染
AI 生成的代码直接用了 uniapp 的 uni-virtual-list 组件。这个组件我之前知道,但总觉得配置复杂,担心兼容性问题,一直没敢用。AI 却毫不犹豫地用了,而且配置得很干净。
核心思路是只渲染当前可见区域内的列表项,超出视口的 dom 节点被回收。比如一个 500 条数据的列表,实际 dom 节点可能只有 20 个。这直接解决了滑动卡顿的问题。
AI 生成的代码大致长这样(我做了简化):
javascript
{{ item.name }}
{{ item.price }}
而我之前手动写的是嵌套在 scroll-view 里的 v-for。两者性能差距在真机上非常明显:同样 300 条数据,用虚拟列表的页面滑动帧率稳定在 55fps 以上,而我的老写法在低端机上只有 20fps 左右。
坑点注意:uni-virtual-list 要求列表项高度固定,否则会计算错位。如果你的列表项高度不固定(比如有的商品描述文字多、有的少),需要提前做高度估算,或者用 item-key 配合动态高度。AI 在这里没处理动态高度,我是后来手动加了个 setTimeout 重新计算高度才解决的。
- 图片懒加载 + 内存回收:AI 自动加了“垃圾回收”
另一个让我惊讶的点是,AI 在图片加载上做了两层优化:
- 第一层:用 lazy-load 属性,让图片只在进入视口时才加载。
- 第二层:在 onUnload 生命周期里,手动清理图片缓存。
第二层优化我从来没想到过。小程序不像浏览器,它的内存管理很保守,大量图片加载后如果不释放,会导致页面越来越卡。AI 生成的代码里,这样写:
javascript
onUnload() {
this.goodsList.forEach(item => {
if (item.thumb) {
uni.downloadFile({ url: item.thumb, success: (res) => {
// 这里其实应该用 wx.cleanFileCache 之类的方法
// 但 AI 写的是手动释放内存,我改成了调用 SDK 方法
}})
}
})
}
虽然这个写法不够严谨(uni.downloadFile 不负责清理),但它提醒了我一个方向。后来我改成了调用 uni.getSavedFileList 和 uni.removeSavedFile 来清理临时文件。这个优化在用户频繁切换页面时效果很明显,页面回退后不会因为缓存堆积而卡顿。
我踩的坑:AI 生成的代码里,onUnload 中直接循环清理,但如果列表很大(比如 1000 条),这个操作本身就会卡住页面。我后来加了个 nextTick 和分批清理的逻辑,类似这样:
javascript
let batchSize = 50
for (let i = 0; i {
this.goodsList.slice(i, i + batchSize).forEach(...)
}, 0)
}
- 按需更新库存:避免整个列表重渲染
我们项目的库存是实时变化的,用户下单后,其他用户的页面上库存数字要立刻更新。以前我的做法是:收到 WebSocket 推送后,重新请求整个列表数据,然后覆盖 goodsList。这会导致整个列表重新渲染,即使只改了一个商品的库存。
AI 生成的代码里,它用了一个很巧妙的方案:维护一个 stockMap 对象,键是商品 ID,值是库存数量。列表渲染时,直接从 stockMap 读取库存,而不是从商品数据里取。更新时只更新 stockMap 中对应 ID 的值,不触发整个列表的 setData。
代码思路:
javascript
data() {
return {
goodsList: [],
stockMap: {} // { goodsId: stock }
}
},
methods: {
updateStock(goodsId, newStock) {
this.stockMap[goodsId] = newStock
// 只更新 stockMap,不重新设置 goodsList
this.$forceUpdate() // 或者用 Vue.set
}
}
虽然 $forceUpdate 仍然会触发一些组件更新,但比重新设置整个 goodsList 要轻量得多。而且 AI 在模板里用 stockMap[item.id] 而不是 item.stock,这一点我手动改代码时经常忽略。
代价:这个方案会增加内存开销,因为多维护了一个 stockMap 对象。但相比性能提升,这点内存完全可以接受。如果你的列表项超过 10000 条,可以考虑用 Map 代替普通对象,或者用 WeakMap 做自动回收。
AI 不是万能的,需要人工“兜底”
虽然 Cursor 帮我写了不少好代码,但我也发现了一些需要人工处理的问题:
-
虚拟列表的滚动事件兼容性:uni-virtual-list 在 iOS 上偶尔会出现滚动位置偏移,AI 没处理。我手动加了一个 @scroll 事件监听,用 scrollTop 做二次校准。
-
图片懒加载的占位图:AI 生成的代码没给 image 加 placeholder 属性,导致图片加载前显示空白,用户体验不好。我手动加了 @error 和 @load 事件来处理加载失败和成功。
-
库存更新的并发问题:如果 WebSocket 推送太快(比如秒杀场景),stockMap 的更新可能会覆盖。我加了一个队列机制,保证每次更新都是基于最新值。
-
代码可读性:AI 生成的代码虽然高效,但变量命名很随意(比如 item、temp、arr)。如果不重命名,团队协作时别人看不懂。我花了半小时把变量名改成有业务含义的。
总结:AI 帮我打开了性能优化的新视角
这次用 Cursor 写 uniapp 小程序的经历,让我意识到两件事:
- 第一,AI 在性能优化上的“直觉”比很多开发者都强,因为它训练的数据里包含了大量真实项目的性能优化模式,而这些模式我们平时很少主动学习。
- 第二,AI 不能替代开发者的判断力,但可以作为一个“性能顾问”,帮你指出那些你根本没想到的优化点。
如果你也在用 uniapp 做小程序,强烈建议试试让 AI 帮你生成列表页、详情页这类高频渲染的页面。但记得,AI 输出的代码要逐行审查,尤其是边界条件和内存管理。毕竟,最懂你业务逻辑的,还是你自己。
最后,如果你也在用 Cursor 或者 Copilot 写 uniapp,欢迎在评论区分享你遇到的坑和优化技巧。





