今天 我们说一个场景
我们可以编写代码如下
@Entry
@Component
struct Index {@State name:string = "小猫猫";build() {Row() {Column() {Text(this.name)Button("改个name").onClick(() => {this.name = this.name == "小猫猫"?"小狗狗":"小猫猫";})son()}.width('100%')}.height('100%')}
}@Component
struct son {build() {Row() {Column() {Text("子组件")grandson()}}}
}@Component
struct grandson {build() {Row() {Column() {Text("底层组件")}}}
}
简单捋一下 我们index组件上挂了@Entry修饰器 说明 第一次进入page 默认访问 index组件
然后 他定义了一个name 用@State修饰 说明这是个响应式数据
然后 index 调用了 son 组件
son 又调用了 grandson 组件
运行结果如下
那么 如果我们想将index 组件内的name 传给 grandson 呢?
之前 我们说的 @Link 其实 你一层一层传下来是可以的 但是 如果中间隔离十几二十个组件呢?
一层一层传下来 就显得有点捞了
这里 我们就要带出一对新的修饰器 @Provide 和 @Consume
我们可以这样写
@Entry
@Component
struct Index {@Provide name:string = "小猫猫";build() {Row() {Column() {Text(this.name)Button("改个name").onClick(() => {this.name = this.name == "小猫猫"?"小狗狗":"小猫猫";})son()}.width('100%')}.height('100%')}
}@Component
struct son {build() {Row() {Column() {Text("子组件")grandson()}}}
}@Component
struct grandson {@Consume name:stringbuild() {Row() {Column() {Text(this.name)Button("改个name").onClick(() => {this.name = "小海豚";})}}}
}
我们用 Provide 声明name 表示 将变量提供给后代组件
然后 我们在 grandson 组件中去取 通过@Consume 这里注意 需要同名 然后 类型相同即可
运行结果如下
且无论是在 哪一个组件 修改这个值 都是可以互相响应的
这个数据传递还是个双向的 非常的好用
如果说 你不想同名 我们可以这样
@Entry
@Component
struct Index {@Provide("name") name:string = "小猫猫";build() {Row() {Column() {Text(this.name)Button("改个name").onClick(() => {this.name = this.name == "小猫猫"?"小狗狗":"小猫猫";})son()}.width('100%')}.height('100%')}
}@Component
struct son {build() {Row() {Column() {Text("子组件")grandson()}}}
}@Component
struct grandson {@Consume("name") userName:stringbuild() {Row() {Column() {Text(this.userName)Button("改个name").onClick(() => {this.userName = "小海豚";})}}}
}
括号后面跟一个别名即可 我们这里都叫name