HarmonyOS鸿蒙Next中@State可以声明interface对象吗?
HarmonyOS鸿蒙Next中@State可以声明interface对象吗? @State可以声明interface对象吗?是否可以传递
interface HSNavigationInterface {
title: string
}
@Component
struct HSNavView {
@Prop dataInfo: HSNavigationInterface
build() {
Row() {
Text(this.dataInfo.title)
}
}
}
interface HSCommonViewInterface {
navData: HSNavigationInterface,
}
@Component
struct HSCommonView {
@Prop dataInfo: HSCommonViewInterface
build() {
Row() {
HSNavView({ dataInfo: this.dataInfo.navData })
}
}
}
@Entry({ routeName: 'HSTestPage' })
@Component
export struct HSTestPage {
[@State](/user/State) pageData: HSCommonViewInterface = {
navData: {
title: "123"
}
}
build() {
Column() {
HSCommonView({ dataInfo: this.pageData })
Text("点击")
.onClick(() => {
this.pageData.navData.title = "456"
})
}
}
}
为什么点击不生效?
更多关于HarmonyOS鸿蒙Next中@State可以声明interface对象吗?的实战教程也可以访问 https://www.itying.com/category-93-b0.html
@State是支持声明interface对象的。但是无法监听到嵌套类对象属性变化。我稍微改了您的代码,像这种简单class的属性是可以监听到的。修改后的参考代码以下:
interface HSNavigationInterface {
title: string
}
@Component
struct HSNavView {
@Prop dataInfo: HSNavigationInterface
build() {
Row() {
Text(this.dataInfo.title)
}
.width('80%')
}
}
@Entry({ routeName: 'HSTestPage' })
@Component
export struct HSTestPage {
[@State](/user/State) pageData: HSNavigationInterface = {
title : '789'
}
build() {
Column() {
HSNavView({dataInfo: this.pageData})
Button('点击')
.width(300)
.height(50)
.onClick(() => {
this.pageData.title = "456"
})
}
}
}
更多关于HarmonyOS鸿蒙Next中@State可以声明interface对象吗?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,@State
装饰器用于声明组件的状态变量,通常用于基本数据类型或简单的对象类型。@State
不支持直接声明interface
对象,因为interface
是类型定义,而不是具体的实例。@State
需要的是一个具体的对象实例,而不是类型定义。如果需要管理复杂对象的状态,可以使用@Observed
和@ObjectLink
来实现。
在HarmonyOS鸿蒙Next中,@State
注解主要用于管理组件内部的简单状态变量,如基本数据类型或简单的对象。@State
不支持直接声明interface
对象,因为interface
是抽象类型,无法实例化。如果需要管理复杂对象的状态,建议使用class
并确保其实现Parcelable
或Serializable
接口,以便在状态恢复时保持数据的完整性。