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

3 回复

@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并确保其实现ParcelableSerializable接口,以便在状态恢复时保持数据的完整性。

回到顶部