Harmony管理组件状态

1、组件内的状态管理:@State

@Component
struct MyComponent {
  @State count: number = 0;

  build() {
    Button("点击")
      .onClick(() => {
        this.count += 1;
      })
  }
}

2、从父组件单向同步状态:@Prop

@Entry
@Component
struct ParentComponent {
  @State countValue: number = 10;

  build() {
    Column() {
      // 父组件的修改会同步给子组件
      Button(`点击`).onClick(() => {
        this.countValue += 1;
      })
      ChildComponent({ count: this.countValue })
    }
  }
}


@Component
struct ChildComponent {
  @Prop count: number = 1;
  build() {
    Column() {
      // @Prop装饰的变量不会同步给父组件
      Button(`点击`).onClick(() => {
	      if(this.count>1){
	         this.count -= 1;
		 }
      })
    }
  }
}

3、与父组件双向同步状态:@Link

<

猜你喜欢

转载自blog.csdn.net/xiaopihair123/article/details/132480154