Read the original article:What is the difference between this and $ in HarmonyOS development?
What is the difference between this and $ in HarmonyOS development?
Problem Description
During HarmonyOS development learning, based on the official documentation for the @Link decorator (parent-child two-way synchronization), the following question arises: Why does line 31 in the code use the state variable with $ instead of this.yellowButtonProp? What is the difference between this and $?
Background Knowledge
Starting from API version 9, the syntax for initializing a child component's @Link from a parent component's @State supports both:
Comp({ aLink: this.aState })
Comp({ aLink: $aState })
Differences between this and $:
- this: Refers to the current instance. Accessing or modifying
this.xxxaffects only the current instance and usually does not trigger re-rendering. Passing data viathisdoes not automatically update child components. - $: Represents a special data-binding mechanism. Accessing or modifying
$xxxaffects the state and triggers re-rendering. Passing data via$establishes two-way binding with the child component.
Solution
Declare state variables in the parent component using @State.
Modify state variables in the parent component via this.xxx in event handlers.
Initialize child components with the parent’s state variables:
- Use
this.xxxfor simple value passing (one-way). - Use
$xxxfor two-way binding between parent and child.
Update the parent state to see automatic updates in child components when using $.
@Entry
@Component
struct ShufflingContainer {
@State greenButtonState: GreenButtonState = new GreenButtonState(180);
@State yellowButtonProp: number = 180;
build() {
Column() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
// Simple type data synchronization from parent component @State to child component @Link
Button('Parent View: Set yellowButton')
.width(312)
.height(40)
.margin(12)
.fontColor('#FFFFFF, 90%')
.onClick(() => {
this.yellowButtonProp = (this.yellowButtonProp < 700) ? this.yellowButtonProp + 40 : 100;
})
// Class type data synchronization from parent component @State to child component @Link
Button('Parent View: Set GreenButton')
.width(312)
.height(40)
.margin(12)
.fontColor('#FFFFFF, 90%')
.onClick(() => {
this.greenButtonState.width = (this.greenButtonState.width < 700) ? this.greenButtonState.width + 100 : 100;
})
// Initialize @Link with class type (two-way binding)
GreenButton({ greenButtonState: $greenButtonState }).margin(12)
// Initialize @Link with simple type (two-way binding)
YellowButton({ yellowButtonState: $yellowButtonProp }).margin(12)
}
}
}
}
Verification Result
Using $ ensures that when yellowButtonProp or greenButtonState changes in the parent, the child components update automatically.
Using this would require explicit reassignment to trigger child updates.
Top comments (0)