1、父传子@State和@Prop
父组件
// 导入子组件
import Child01 from '../components/Child01'
@Entry
@Component
struct StateExample {
@State count: number = 0
build() {
Column() {
Text("计数器 count:" + this.count)
Button('count + 1').onClick(() => {
// 这里使用 this.count++ 会有问题
this.count += 1
})
Child01({ a: this.count }).margin({ top: 10 })
}.width('100%')
.height(300)
}
}
子组件
@Component
export default struct Child01 {
// 使用@Prop定义父传子数据,数据单向流动
@Prop a: number;
build() {
Column() {
Text('我是子组件Child1')
Text('父组件传递的count: ' + this.a)
Button('修改父组件count数据').onClick(() => {
this.a -= 1
}).margin({bottom:5})
}.width('100%').border({ width: 1, color: Color.Black })
}
}
注意:使用@State和@Prop进行父子组件数据通信时,数据流是单向的;父组件修改count子组件可以动态更新,而子组件无法修改父组件的数据
2、父子通信@Link($state属性)
父组件
// 导入子组件
import Child02 from '../components/Child02'
@Entry
@Component
struct StateExample {
@State count1: number = 199
build() {
Column() {
Text("计数器 count1:" + this.count1)
Button('count1 + 1').onClick(() => {
// 这里使用 this.count++ 会有问题
this.count1 += 1
}).margin({ top: 5 })
Child02({ b: $count1 }).margin({ top: 10 })
}.width('100%')
.height(300)
}
}
子组件
@Component
export default struct Child02 {
// @Link 实现父子组件的双向流动
@Link b:number ;
build() {
Column({space:10}){
Text('我是子组件Child2')
Text('父组件传递过来的count1: '+this