
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
相信大家都有这样一个疑问,如何在app.ets中定义全局对象(全局变量、方法),又如何在其它ets文件中获取并应用它?
在js方式中在app.js中定义了对象,可以在自定义js文件中通过getApp()获取app.js中暴露的对象。
那么问题就来了:在app.ets下,如何实现呢?
另外,当app.ets中全局变量的值改变时,其它引用的界面会自动刷新吗?如何做到?
其实FA模型使用globalThis能够实现全局变量共享。
先来看一下效果:
现在来看一下,我们是如何实现的。
export default {
onCreate() {
console.info('Application onCreate')
globalThis.title = 'OpenHarmony'
},
onDestroy() {
console.info('Application onDestroy')
},
}
/*
* Copyright (c) 2021 JianGuo Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@Entry
@Component
struct Global {
@State title: string = ''
aboutToAppear(){
this.title = globalThis.title
}
build() {
Row() {
Column() {
Text(this.title)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
需要注意的是globalThis必须要保持一致,不然是得不到值的。
这个也是给我们一些启示,我们可以用来做一下全局的处理,将一些常用的东西可以封装在此,全局使用
在Flutter中也是经常遇到这样的问题。如果不把一些常用的组件封装,那么你的代码将会显得十分啰嗦,而且不易阅读,那么这个时候我们就需要来抽取一下
@Entry
@Component
struct Global {
@State title: string = ''
aboutToAppear(){
this.title = globalThis.title
}
@Builder CustomTitle(text:string) {
Text(text)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.margin({ top: 10, bottom: 10 })
}
build() {
Row() {
Column() {
this.CustomTitle('1、加油:')
this.CustomTitle('2、努力:')
Text(this.title)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
通过@Builder CustomTitle来进行封装。
先定义
// Text公共样式
@Extend(Text) function commonStyle () {
.width('100%')
.fontSize(14)
}
Column() {
Text('abc,').commonStyle().textCase(TextCase.LowerCase)
Text('abc').commonStyle().textCase(TextCase.UpperCase)
}
再使用。
好的,今天 的文章就写到这。