/** * 父子组件双向互绑定 */ // 自定义按钮的信息类型 class ButtonState { value:string width:number constructor(value:string,width:number) { this.value = value this.width = width } } @Component struct MyChildGreenButton { // 拥有绿色按钮的组件,Link装饰器实现双向同步 @Link buttonState: ButtonState build(){ Button(`${this.buttonState.value}`) .width(this.buttonState.width) .height(150) .backgroundColor(Color.Green) .onClick(()=>{ if (this.buttonState.width < 700) { this.buttonState.width += 100 } else { this.buttonState = new ButtonState('绿色按钮', 100) } }) } } @Component struct MyChildRedButton { // 拥有红色按钮的组件,Link装饰器实现双向同步 @Link value : string @Link buttonWidth:number build(){ Button(`${this.value}`) .width(this.buttonWidth) .height(150) .backgroundColor(Color.Red) .onClick(()=>{ this.buttonWidth += 50 }) } } @Entry @Component struct MyParent { @State parentGreenButton:ButtonState = new ButtonState('壹号子组件',300) @State parentRedValue: string = '二号子组件' @State parentRedWidth: number = 200 // h红按钮的宽度 build(){ Column() { // 父组件中调整按钮的宽度 Button(`父组件中修改绿色按钮的宽度:${this.parentGreenButton.width}`) .onClick(()=>{ this.parentGreenButton.width = this.parentGreenButton.width < 700 ? this.parentGreenButton.width + 100 : 100 }) Button(`父组件中修改红色按钮的宽度:${this.parentRedWidth}`) .onClick(()=>{ this.parentRedWidth = this.parentRedWidth < 700 ? this.parentRedWidth + 100 : 100 }) Divider() MyChildGreenButton({buttonState: $parentGreenButton}) MyChildRedButton({value:$parentRedValue, buttonWidth: $parentRedWidth}) } } }
标签:ArkTS,buttonState,绑定,value,width,按钮,组件,parentRedWidth From: https://www.cnblogs.com/zhzhang/p/17964218