@CustomEnv:自定义环境变量
@CustomEnv可用于获取自定义环境变量。开发者可通过WithEnv组件的.customEnv接口设置自定义环境变量,在子组件中通过@CustomEnv装饰器读取相同CustomEnvKey<S>对应的变量值。该机制实现了组件树间的数据透传,使父子组件能基于环境变量进行联动,同时保持代码解耦。
说明:
从API版本26.0.0开始,@CustomEnv支持在@Component和@ComponentV2中使用。
从API版本26.0.0开始,该装饰器支持在原子化服务中使用。
概述
@CustomEnv是响应式自定义环境变量装饰器,其功能包括:
- 根据入参读取相应的自定义环境变量信息,详情见@CustomEnv使用方法。
- 自定义环境变量改变时,通知@CustomEnv装饰的变量更新,并触发@CustomEnv关联组件刷新,以实现界面内容的更新。
- 使用@CustomEnv装饰的变量具有只读特性,不允许在组件内直接赋值。若需更新该变量的值,必须通过父组件的WithEnv组件配合
.customEnv()方法进行更新。尝试对@CustomEnv变量进行本地赋值将导致编译错误。
开发者可以根据自定义key使用@CustomEnv装饰器声明响应式环境变量,实现组件间的状态共享。示例如下:
const custom = CustomEnvKey.create<number>();
@CustomEnv(custom) varName: string = 'default value';
其中:
-
custom:开发者自定义的环境变量key,类型为CustomEnvKey<S>,需使用const关键字全局定义,否则会编译报错。 -
varName:装饰的变量名。 -
'default value':变量的默认值,当未找到对应的WithEnv组件提供的值时使用。
@CustomEnv使用方法
装饰器说明
| @CustomEnv装饰器 | 说明 |
|---|---|
| 装饰器参数 | @CustomEnv装饰器的入参必须为CustomEnvKey<S>类型。 |
| 可装饰的变量类型 | Object、class、string、number、boolean、enum等基本类型以及Array、Date、Map、Set等内置类型。支持null、undefined以及联合类型。 |
| 装饰变量的初始值 | 必须本地初始化,不允许外部传入初始化。 |
变量传递
| 传递规则 | 说明 |
|---|---|
| 从父组件初始化 | @CustomEnv装饰的变量仅允许本地初始化,无法从外部传入初始化。 |
| 本地初始化向上查找 | @CustomEnv装饰器向上查找父组件时,递归查找父组件,查找WithEnv通过customEnv设置的相同key的值。 |
观察变化
当点击更新按钮导致@Local装饰的变量值发生变化时,WithEnv组件中通过.customEnv()方法设置的值也会通知@CustomEnv,此时子组件中@CustomEnv装饰的变量将更新最新值并触发界面重新渲染,实现了完整的响应式更新链路。
const custom = CustomEnvKey.create<string>();
@Entry
@ComponentV2
struct Index {
@Local customMsg: string = 'Hello';
build() {
Column() {
Button('update')
.onClick(() => {
this.customMsg = 'Hello World';
})
WithEnv() {
// 有WithEnv组件,显示this.customMessage的默认值'Hello',点击Button后值更新为'Hello World'。
Child()
}.customEnv(custom, this.customMsg)
}
}
}
@ComponentV2
struct Child {
@CustomEnv(custom) customMessage: string = 'default content';
build() {
Column() {
Text(`Child: ${this.customMessage}`);
}
}
}
@CustomEnv和@Env能力对比
@CustomEnv和@Env都是环境变量相关,但两者能力有较大的不同,具体能力对比见下表。
| 能力 | @CustomEnv | @Env |
|---|---|---|
| 起始API version | 从API版本26.0.0开始支持。 | 从API version 22开始支持。 |
| 支持参数 | 开发者自定义的CustomEnvKey类型对象。 | SystemProperties的枚举值。 API版本26.0.0之后支持SystemProperties|SystemEnvKey<T>类型参数。 |
| 使用形式 | @CustomEnv为装饰器,可声明在@Component或@ComponentV2中,开发者通过WithEnv的customEnv接口设置的环境变量 | @Env为装饰器,可声明在@Component或@ComponentV2中,直接读取系统环境变量。 API版本26.0.0之后,开发者可通过WithEnv的env接口设置SystemEnvKey<T>类型参数的系统环境变量。 |
| 值的来源 | 初始化给定默认值或通过WithEnv组件的.customEnv()方法设置。 | 通过WithEnv的env接口设置的系统环境变量。 |
| 是否有响应式能力 | 有,当WithEnv设置的值变化时,会通知@CustomEnv装饰的变量更新,并通知关联组件刷新。 | 有,当系统环境变量变化时,会通知@Env装饰的变量更新,并通知关联组件刷新。 |
限制条件
- @CustomEnv仅支持在@Component和@ComponentV2中使用,否则会有编译时报错。如果开发者绕过编译时检查,则会有运行时报错。
const custom = CustomEnvKey.create<string>();
class CustomEnvKey {
@CustomEnv(custom) customVarName: string = 'hello world'; // 错误用法,编译时报错
}
const custom = CustomEnvKey.create<string>();
@Entry
@Component
struct Index {
@CustomEnv(custom) customVarName: string = 'hello world'; // 正确用法
}
- @CustomEnv装饰的变量为只读属性,不允许开发者进行赋值操作,否则会有编译时报错。如果开发者绕过编译时检查,则会有运行时报错。
const custom = CustomEnvKey.create<string>();
@Entry
@ComponentV2
struct Index {
@CustomEnv(custom) customVarName: string = 'hello world';
@Local newVarName: string = 'customMessage';
build() {
Column() {
Button('update')
.onClick(() => {
this.customVarName = 'Change Message'; // 错误用法,编译时报错
})
WithEnv() {
Child()
}.customEnv(custom, this.newVarName)
}
}
}
- @CustomEnv装饰的变量不能通过父组件传参进行初始化;若在组件实例化时以参数形式赋值,编译阶段会进行拦截并报错。
const custom = CustomEnvKey.create<string>();
@Entry
@ComponentV2
struct PageOne {
@CustomEnv(custom) defaultMessage: string = 'Hello';
build() {
Column() {
Child({ firstValue: this.defaultMessage }) // 错误用法,编译时报错
}
}
}
@ComponentV2
struct Child {
@CustomEnv(custom) firstValue: string = 'world';
build() {
Column() {
Text(this.firstValue)
}
}
}
- @CustomEnv入参类型必须是CustomEnvKey类型,若传入非CustomEnvKey类型,将在编译时进行校验。如果开发者通过类型断言(as)绕过编译检查,则会有运行时报错。
@Entry
@ComponentV2
struct Index {
// 传入的非法类型key断言为合法类型,绕过编译检查,运行时会报错
@CustomEnv(123 as CustomEnvKey<string>) customVarName: string = 'hello world'; // 错误用法,运行时报错
}
- @CustomEnv不会向上查找@Component/@ComponentV2中相同Key的@CustomEnv设置的值。
const custom = CustomEnvKey.create<string>();
@Entry
@ComponentV2
struct Index {
@Local customMsg: string = 'Hello';
@CustomEnv(custom) customMessage: string = 'parent';
build() {
Column() {
Child()
}
}
}
@ComponentV2
struct Child {
@CustomEnv(custom) customMessage: string = 'child';
build() {
Column() {
Text(`Child: ${this.customMessage}`);
}
}
}
@CustomEnv初始化流程
@CustomEnv变量初始化遵循以下流程:
- 从WithEnv组件中查找已有实例:
- 查找父组件是否为WithEnv组件。
- 如果不是WithEnv,则继续向上查找,直到查找到根节点。
- 若找到对应key的WithEnv组件,则获取组件提供的环境变量值并赋值给@CustomEnv装饰的变量。
- 使用声明的变量初始值。
- 如果未找到对应的WithEnv组件,则使用CustomEnv装饰变量的本地初始值。
流程图如下。
[图示请参阅官方原文]
使用场景
支持自定义key和value
新增的状态管理装饰器@CustomEnv支持自定义key配置,并且可以指定变量的初始值。语法格式为:@CustomEnv(custom) customVarName: string = 'hello world'。其中'custom'为开发者自定义的环境变量key,'hello world'为该变量的初始值。
const custom = CustomEnvKey.create<string>();
@Entry
@ComponentV2
struct Index {
// 1. 实现了定义的key及value
@CustomEnv(custom) customVarName: string = 'hello world';
build() {
Column() {
Text(this.customVarName)
}
}
}
@CustomEnv支持多种数据类型
@CustomEnv支持简单类型和复杂类型的变量声明。简单类型包括string、number、boolean、enum等;复杂类型包括class、Object等对象类型。
const custom = CustomEnvKey.create<string>();
@Entry
@ComponentV2
struct Index {
@CustomEnv(custom) customVarName: string = 'hello world';
}
const custom = CustomEnvKey.create<number>();
@Entry
@ComponentV2
struct Index {
@CustomEnv(custom) customVarName: number = 1;
}
const custom = CustomEnvKey.create<boolean>();
@Entry
@ComponentV2
struct Index {
@CustomEnv(custom) customVarName: boolean = true;
}
@ObservedV2
class CustomEnvValue {
@Trace id: number = 123;
@Trace userName: string = 'admin';
}
const custom = CustomEnvKey.create<CustomEnvValue>();
@Entry
@ComponentV2
struct Index {
@CustomEnv(custom) customVarName: CustomEnvValue = new CustomEnvValue();
}
@CustomEnv支持默认初始值
当子组件中使用@CustomEnv装饰的变量向上查找环境变量值但未找到匹配的WithEnv组件时,该变量将使用声明时指定的初始值作为默认值。
const custom = CustomEnvKey.create<string>();
@Entry
@ComponentV2
struct Index {
build() {
Column() {
Child()
}
}
}
@ComponentV2
struct Child {
@CustomEnv(custom) customMessage: string = 'default content';
build() {
Column() {
// 此时Text中的内容显示为: Child: default content
Text(`Child: ${this.customMessage}`);
}
}
}
环境变量查找遵循就近原则
子组件中使用@CustomEnv装饰的变量在获取环境变量值时,会向上遍历组件树查找对应的WithEnv组件,并优先选择距离当前子组件最近的WithEnv组件所提供的值。当最近的WithEnv组件未定义该key时,会继续向更外层查找,直至找到匹配值,如果未找到匹配值,则使用本地默认值。
以下示例中,Child组件中声明@CustomEnv(custom)将被离它最近的内层WithEnv赋值,最终值为'the nearest WithEnv'。
const custom = CustomEnvKey.create<string>();
@Entry
@ComponentV2
struct Index {
build() {
Column() {
// 就近原则体现
WithEnv() {
// 优先查找该层WithEnv
WithEnv() {
// 就近原则,显示'the nearest WithEnv'
Child()
}.customEnv(custom, 'the nearest WithEnv')
}.customEnv(custom, 'outer WithEnv')
}
}
}
@ComponentV2
struct Child {
// @CustomEnv会向上查找父组件,优先查找WithEnv
@CustomEnv(custom) customMessage: string = 'default content';
build() {
Column() {
Text(`Child: ${this.customMessage}`);
}
}
}
响应式更新能力
当点击更新按钮导致@Local装饰的变量值发生变化时,WithEnv组件中通过.customEnv()方法设置的值也会通知@CustomEnv,此时子组件中@CustomEnv装饰的变量将更新最新值并触发界面重新渲染,实现了完整的响应式更新链路。
const custom = CustomEnvKey.create<string>();
@Entry
@ComponentV2
struct Index {
@Local customMsg: string = 'Hello';
build() {
Column() {
Button('update')
.onClick(() => {
this.customMsg = 'Hello World';
})
WithEnv() {
// 有WithEnv组件,显示this.customMessage的默认值'Hello',点击Button后值更新为'Hello World'。
Child()
}.customEnv(custom, this.customMsg)
}
}
}
@ComponentV2
struct Child {
@CustomEnv(custom) customMessage: string = 'default content';
build() {
Column() {
Text(`Child: ${this.customMessage}`);
}
}
}
运行效果图如下。
[图示请参阅官方原文]
@CustomEnv装饰变量支持@Monitor监听变化
当父组件通过WithEnv更新对应环境值时,子组件中@CustomEnv变量会变更,并触发@Monitor回调。
const custom = CustomEnvKey.create<number>();
@Entry
@ComponentV2
struct MonitorTest {
@Local message: number = 20;
build() {
Row() {
Column() {
Button('change message').onClick(() => {
this.message++;
})
WithEnv() {
Child()
}.customEnv(custom, this.message)
}
.width('100%')
}
.height('100%')
}
}
@ComponentV2
struct Child {
@CustomEnv(custom) message: number = 0;
@Monitor('message')
onStrChange(monitor: IMonitor) {
monitor.dirty.forEach((path: string) => {
hilog.info(0x0000, 'testTag',
`${path} changed from ${monitor.value(path)?.before} to ${monitor.value(path)?.now}`);
});
}
build() {
Column() {
Text('message' + `${this.message}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
}
}
在上面的示例中:
点击'change message'更改message的值,将会触发@Monitor装饰器的回调并输出对应日志。
运行效果图如下。
[图示请参阅官方原文]
@CustomEnv支持组件冻结
当@CustomEnv所在组件处于非激活状态的时候,WithEnv对应的key发生改变时,将不会通知非激活状态下@Monitor装饰器的回调,当非激活状态的@CustomEnv回到激活状态时,将会通知@Monitor装饰器的回调。
需要注意的是:在首次渲染的时候,Tab只会创建当前正在显示的TabContent,当切换所有TabContent后,TabContent才会被全部创建。
const custom = CustomEnvKey.create<number>();
@Entry
@ComponentV2
struct TabContentTest {
@Local message: number = 20;
@Local data: number[] = [0, 1];
build() {
Row() {
Column() {
Button('change message').onClick(() => {
this.message++;
})
WithEnv() {
Tabs() {
ForEach(this.data, (item: number) => {
TabContent() {
FreezeChild()
}.tabBar(`tab${item}`)
}, (item: number) => item.toString())
}
}.customEnv(custom, this.message)
}
.width('100%')
}
.height('100%')
}
}
@ComponentV2({ freezeWhenInactive: true })
struct FreezeChild {
@CustomEnv(custom) message: number = 0;
@Param index: number = 0;
@Monitor('message')
onStrChange(monitor: IMonitor) {
monitor.dirty.forEach((path: string) => {
hilog.info(0x0000, 'testTag',
`${path} changed from ${monitor.value(path)?.before} to ${monitor.value(path)?.now}`);
});
}
build() {
Column() {
Text('message' + `${this.message}, index: ${this.index}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
}
}
在上面的示例中:
-
点击'change message'更改message的值,当前正在显示的TabContent组件中的@Monitor中注册的方法onStrChange被触发。
-
点击TabBar中的'tab1'切换到另外的TabContent,TabContent状态由inactive变为active,对应的@Monitor中注册的方法onStrChange被触发。
-
再次点击'change message'更改message的值,仅当前显示的TabContent子组件中的@Monitor中注册的方法onStrChange被触发。其他inactive的TabContent组件不会触发@Monitor。
运行效果图如下。
[图示请参阅官方原文]
装饰Array类型变量
当装饰的对象是Array时,可以通过调用Array的接口push,pop,shift,unshift,splice,copyWithin,fill,reverse,sort更新Array中的数据。
class Fruit {
public name: string;
constructor(name: string) {
this.name = name;
}
}
const custom = CustomEnvKey.create<Fruit[]>();
@Entry
@ComponentV2
struct Index {
@CustomEnv(custom) fruits: Fruit[] = [new Fruit('apple'), new Fruit('banana')]; // 使用@CustomEnv装饰Array类型变量
build() {
Row() {
Column() {
ForEach(this.fruits, (item: Fruit) => {
Text(`${item.name}`)
.fontSize(20)
.margin(10)
})
// 新增数组元素,触发UI刷新
Button('Push element')
.onClick(() => {
this.fruits.push(new Fruit('cherry'));
})
.width(300)
.margin(10)
// 翻转数组元素,触发UI刷新
Button('Reverse array')
.onClick(() => {
this.fruits.reverse();
})
.width(300)
.margin(10)
// 使用同一元素填充数组,触发UI刷新
Button('Fill array')
.onClick(() => {
this.fruits.fill(new Fruit('apple'));
})
.width(300)
.margin(10)
}
.width('100%')
}
.height('100%')
}
}
运行效果图如下。
[图示请参阅官方原文]
装饰Date类型变量
当装饰的对象是Date时,可通过调用Date的接口setFullYear,setMonth,setDate,setHours,setMinutes,setSeconds,setMilliseconds,setTime,setUTCFullYear,setUTCMonth,setUTCDate,setUTCHours,setUTCMinutes,setUTCSeconds,setUTCMilliseconds更新Date的属性。
const custom = CustomEnvKey.create<Date>();
@Entry
@ComponentV2
struct DatePickerExample {
@CustomEnv(custom) selectedDate: Date = new Date('2021-08-08'); // 使用@CustomEnv装饰Date类型变量
build() {
Row() {
Column() {
// 调用Date的setFullYear接口修改年份,触发UI刷新
Button('increase the year by 1')
.onClick(() => {
this.selectedDate.setFullYear(this.selectedDate.getFullYear() + 1);
})
.margin(10)
.width(300)
// 调用Date的setMonth接口修改月份,触发UI刷新
Button('increase the month by 1')
.onClick(() => {
this.selectedDate.setMonth(this.selectedDate.getMonth() + 1);
})
.margin(10)
.width(300)
// 调用Date的setDate接口修改日期,触发UI刷新
Button('increase the day by 1')
.onClick(() => {
this.selectedDate.setDate(this.selectedDate.getDate() + 1);
})
.margin(10)
.width(300)
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.selectedDate
}).margin(20)
}
.width('100%')
}
.height('100%')
}
}
运行效果图如下。
[图示请参阅官方原文]
装饰Map类型变量
当装饰的对象是Map时,可以通过调用Map的接口set,clear,delete更新Map中的数据。
const custom = CustomEnvKey.create<Map<string, number>>();
@Entry
@ComponentV2
struct MapSample {
@CustomEnv(custom) fruits: Map<string, number> = new Map([['apple', 1], ['banana', 2]]); // 使用@CustomEnv装饰Map类型变量
build() {
Row() {
Column() {
ForEach(Array.from(this.fruits.entries()), (item: [string, number]) => {
Text(`key: ${item[0]}, value: ${item[1]}`)
.fontSize(20)
.margin(10)
})
// 新增键值对,触发UI刷新
Button('Set entry cherry')
.onClick(() => {
this.fruits.set('cherry', 3);
})
.width(300)
.margin(10)
// 更新键值对,触发UI刷新
Button('Update entry apple')
.onClick(() => {
this.fruits.set('apple', 4);
})
.width(300)
.margin(10)
// 删除键值对,触发UI刷新
Button('Delete entry apple')
.onClick(() => {
this.fruits.delete('apple');
})
.width(300)
.margin(10)
// 清空Map,触发UI刷新
Button('Clear map')
.onClick(() => {
this.fruits.clear();
})
.width(300)
.margin(10)
}
.width('100%')
}
.height('100%')
}
}
运行效果图如下。
[图示请参阅官方原文]
装饰Set类型变量
当装饰的对象是Set时,可以通过调用Set的接口add,clear,delete更新Set中的数据。
const custom = CustomEnvKey.create<Set<string>>();
@Entry
@ComponentV2
struct SetSample {
@CustomEnv(custom) fruits: Set<string> = new Set(['apple', 'banana']); // 使用@CustomEnv装饰Set类型变量
build() {
Row() {
Column() {
ForEach(Array.from(this.fruits.entries()), (item: [string, string]) => {
Text(`${item[0]}`)
.fontSize(20)
.margin(10)
})
// 新增元素,触发UI刷新
Button('Add element')
.onClick(() => {
this.fruits.add('cherry');
})
.width(300)
.margin(10)
// 删除元素,触发UI刷新
Button('Delete element apple')
.onClick(() => {
this.fruits.delete('apple');
})
.width(300)
.margin(10)
// 清空Set,触发UI刷新
Button('Clear set')
.onClick(() => {
this.fruits.clear();
})
.width(300)
.margin(10)
}
.width('100%')
}
.height('100%')
}
}
运行效果图如下。
[图示请参阅官方原文]
@CustomEnv的V1/V2混用
@CustomEnv可以在@Component和@ComponentV2中使用,其遵循V1V2混用的基本规则。@CustomEnv装饰的变量传递给V1时,遵循V1状态变量装饰器不能和@ObservedV2装饰的class的规则。@CustomEnv装饰的变量传递给V1时,遵循V2只有@Param可以接收外部变量的规则。
- @CustomEnv装饰的变量传递给V1时,遵循V1状态变量装饰器不能接收@ObservedV2装饰的class的规则。
@ObservedV2
class CustomValue {
@Trace defaultVal: string = 'hello';
}
const custom = CustomEnvKey.create<string>();
const custom1 = CustomEnvKey.create<CustomValue>();
@Entry
@ComponentV2
struct PageOne {
@CustomEnv(custom) defaultMessage: string = 'parent Value';
@CustomEnv(custom1) defaultMessage1: CustomValue = new CustomValue();
build() {
Column() {
Text(`Parent Value is :${this.defaultMessage}`)
Child({ message: this.defaultMessage }) // 正确用法
// Child({ message: this.defaultMessage1 }) // 错误用法,编译报错。
}
.height('100%')
.width('100%')
}
}
@Component
struct Child {
@Require @Prop message: string;
// @Prop message1: CustomValue; // 错误用法,V1的状态变量不能和ObservedV2连用。
build() {
Column() {
Text(`Child value is :${this.message}`)
}
.height('100%')
.width('100%')
}
}
- @CustomEnv装饰的变量传递给V2时,遵循V2只有@Param可以接收外部变量的规则。
@ObservedV2
class CustomValue {
@Trace defaultVal: string = 'hello';
}
const custom = CustomEnvKey.create<CustomValue>();
@Entry
@Component
struct PageOne {
@CustomEnv(custom) defaultMessage: CustomValue = new CustomValue();
build() {
Column() {
Text(this.defaultMessage.defaultVal)
Button('update')
.onClick(() => {
this.defaultMessage.defaultVal = 'hello world';
})
Child({ message: this.defaultMessage })
}
.height('100%')
.width('100%')
}
}
@ComponentV2
struct Child {
@Require @Param message: CustomValue;
build() {
Column() {
Text(`Child Value is : ${this.message.defaultVal}`)
}
.height('100%')
.width('100%')
}
}
- @CustomEnv是提供状态管理V2的观察能力,当@CustomEnv装饰的变量是@Observed时,需要调用enableV2Compatibility使能其观察类属性的能力,否则将无法观察类属性的变化。
@Observed
class CustomValue {
@Track defaultVal: string = 'hello';
}
const custom = CustomEnvKey.create<CustomValue>();
@Entry
@ComponentV2
struct PageOne {
@CustomEnv(custom) defaultMessage: CustomValue = UIUtils.enableV2Compatibility(new CustomValue());
build() {
Column() {
Text(this.defaultMessage.defaultVal)
Button('update')
.onClick(() => {
this.defaultMessage.defaultVal = 'hello world';
})
Child({ message: this.defaultMessage })
}
.height('100%')
.width('100%')
}
}
@Component
struct Child {
@ObjectLink message: CustomValue;
build() {
Column() {
Text(`Child value is : ${this.message.defaultVal}`)
}
.height('100%')
.width('100%')
}
}
本文来自 OpenHarmony 文档贡献者,按 CC BY 4.0 整理版式与相对链接,保留正文与代码。图示请参阅原文。作者与贡献记录。
