@Prop数据从父组件传到子组件,子组件不能改父组件的数据,改了也只影响自己。

@Component
@Entry
@Preview
struct Father {
  @State money: number = 100;  // 父亲有100块钱

  build() {
    Column() {
      Text(`父亲有: ${this.money}元`)
      Button('父亲挣钱+10').onClick(() => {
        this.money += 10;  // 父亲自己挣钱,能改
      })
      // 传给孩子50块钱(@Prop是单向的)
      Son({ money: this.money })  // 把money传给孩子
    }
  }
}

// 2. 子组件(孩子)
@Component
struct Son {
  @Prop money: number;  // 接收父组件传过来的值

  build() {
    Column() {
      Text(`孩子有: ${this.money}元`)
      Button('孩子花钱-10').onClick(() => {
        this.money -= 10;  // 孩子能改,但只改自己
        // 注意:父亲的money不会变!
      })
    }
  }

结论:

爸爸点"+10",爸爸变成110,儿子也变成110(父变子跟着变)

儿子点"-10",儿子变成100,但爸爸还是110(子变父不变)

 

@Link 数据在父组件和子组件之间双向同步,任何一方修改,另一方都会变。

// 1. 父组件
@Component
@Entry
struct Father {
  @State money: number = 100;

  build() {
    Column() {
      Text(`父亲有: ${this.money}元`)
      Button('父亲挣钱+10').onClick(() => {
        this.money += 10;
      })

      // 使用$符号建立双向绑定
      Son({ money: $money })  // 注意:$money
    }
  }
}

// 2. 子组件(孩子)
@Component
struct Son {
  @Link money: number;  // @Link接收,不是@Prop

  build() {
    Column() {
      Text(`孩子有: ${this.money}元`)
      Button('孩子花钱-10').onClick(() => {
        this.money -= 10;  // 孩子改了,父亲也跟着改变
      })
    }
  }
}

结论:

爸爸点"+10",爸爸110,儿子也110

儿子点"-10",儿子100,爸爸也100(双向同步)

 

Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐