HarmonyOS 鸿蒙Next 如何实现公共样式在多文件中复用?
HarmonyOS 鸿蒙Next 如何实现公共样式在多文件中复用?
如题,目前通过 @Styles
@Extend
可以实现将样式从 build 中分离同时在文件内实现复用。但这种复用仅限于单个 ets 文件,怎样实现公共样式的跨文件复用呢?类似 less 中的 mixin 那样? 这样代码更容易复用,而且可以将样式和代码在两个编辑器 Tab 中编辑,效率也更高。
目前我的代码如下:
@Component
export struct PageTitle {
@Link isRefreshing: boolean;
@Prop title: string;
build() {
Row(){
Row(){
Image($r('app.media.ic_public_back')).bindBackIconStyles()
Text(this.title).bindTitleStyles()
}
Row(){
Image($r('app.media.loading')).bindRefreshIconStyles()
}
}.bindRootStyles()
}
}
// 样式部分 -------------------------------------
@Extend(Row) function bindRootStyles() {
.justifyContent(FlexAlign.SpaceBetween)
.padding({ left: 10, right: 10 })
.backgroundColor('#0f0')
.width('100%')
.height(47)
}
@Extend(Image) function bindBackIconStyles() {
.margin({right: 18})
.width(21)
.height(28)
}
@Extend(Text) function bindTitleStyles() {
.fontSize(20)
}
@Extend(Image) function bindRefreshIconStyles() {
.width(22)
.height(22)
}
我期望将样式相关代码抽离出来单独在一个文件中维护,类似 HTML 开发中将样式可以在 CSS 中维护一样。我期望的方式:
import { bindRootStyles, bindBackIconStyles, bindTitleStyles, bindRefreshIconStyles } from './styles';
@Component
export struct PageTitle {
@Link isRefreshing: boolean;
@Prop title: string;
build() {
Row(){
Row(){
Image($r('app.media.ic_public_back')).bindBackIconStyles()
Text(this.title).bindTitleStyles()
}
Row(){
Image($r('app.media.loading')).bindRefreshIconStyles()
}
}.bindRootStyles()
}
}
更多关于HarmonyOS 鸿蒙Next 如何实现公共样式在多文件中复用?的实战教程也可以访问 https://www.itying.com/category-93-b0.html
同问,有方案了可以分享下
我也找了半天 搜遍了网络 都说不支持 等官方什么时候支持吧 目前只能写到页面里面了
太难了,
这是转换后的Markdown文档:
这是转换后的Markdown文档:
我还期待把build抽出去呢,实现结构-样式-行为的定义分离
其实 Builder 导出和这个面临的技术问题是一样的,本质上都是类似 C 语言中的宏,只要在进行构建之前进行预处理就可以。可能项目组之前缺乏实际项目经验,没有提前预想到这个问题。
如果是 webpack 还能自己写 loader 和 plugin 处理下,arkts 没有放开编译接口,只能等官方的方案了
这个一直都不支持,我也苦恼该怎么抽离公共样式
在HarmonyOS(鸿蒙Next)中,可以通过定义公共样式资源来实现样式的复用。具体步骤如下:
-
创建样式资源文件:在项目的
resources
目录下,创建一个XML文件用于定义公共样式。例如,可以在resources/base/element
目录下创建一个名为styles.xml
的文件。 -
定义样式:在
styles.xml
文件中,使用<style>
标签定义样式。每个样式可以包含多个属性,例如:
<style name="CommonTextStyle">
<item name="textSize">18fp</item>
<item name="textColor">#000000</item>
</style>
- 引用样式:在其他XML布局文件中,通过
style
属性引用定义的公共样式。例如:
<Text
ohos:width="match_content"
ohos:height="match_content"
ohos:text="Hello, HarmonyOS"
ohos:style="@style/CommonTextStyle"/>
- 样式继承:如果需要基于已有样式进行扩展,可以使用
parent
属性继承样式。例如:
<style name="LargeTextStyle" parent="CommonTextStyle">
<item name="textSize">24fp</item>
</style>
通过以上步骤,可以在多个文件中复用公共样式,提升开发效率并保持UI的一致性。