鸿蒙开发中,请写一个@Prop是父子传参的组件调用格式
时间: 2024-12-19 21:28:56 浏览: 42
在HarmonyOS(鸿蒙)的组件开发中,`@Prop` 是属性装饰器,用于声明组件间的数据绑定。当你想让一个父组件将数据传递给子组件时,可以按照以下格式设置:
假设有一个父组件 `ParentComponent`,它有需要传递给子组件 `ChildComponent` 的属性 `name`,你可以这样定义:
```java
// 父组件 ParentComponent.kt
@Component(modality = ModalityType.PAUSABLE)
class ParentComponent {
@Prop(dataType = String.class) // 定义字符串类型的属性并标记为prop
lateinit var childName: String
// 其他组件方法...
}
// 子组件 ChildComponent.kt
@Component(dependencies = [ParentComponent])
class ChildComponent : ViewComponent<ParentComponent> {
override fun createView(context: Context): View {
val view = View(context)
// 在子组件中接收并处理父组件传来的名字
val name = props.childName
// ...
return view
}
}
```
在父组件实例化时,可以通过`childName` 属性直接传值给子组件:
```kotlin
val parent = ParentComponent(childName = "从父组件传递过来的名称")
parent.show()
```
阅读全文
相关推荐


















