HarmonyOS Hongmeng Study Notes (12) The role of @Link

According to HarmonyOS Hongmeng Study Notes (5) @State Function Description and Simple Cases, we know that when the variable modified by @State changes, the relevant page will be refreshed to update the UI. What if the child component wants to change the state of the parent component to refresh the UI? For example, the following code:
insert image description here

As shown in the code above: PlayButtonthe component is Playerthe child component of the component and Playeris the parent component. Our intention is PlayButtonto click the play or pause button in the component, and the text information Playerof the parent component Textwill change accordingly. Used to simulate the player's play and pause effects. Although the component Playerof the parent component is decorated with @State , the click of the child component has no effect at this time, and the parent component has not changed. So how to solve this problem? At this time, the role of @Link is revealed. The above code only needs to be modified in two ways:isPlayingPlayButtonPlayerText

1. Decorate PlayButtonthe buttonPlaying variable with @Link .

@Component
struct PlayButton {
    
    
 @Link buttonPlaying: boolean 
}

2. When initializing PlayButtonthe component, it needs to be PlayButton({buttonPlaying: this.isPlaying})changed to PlayButton({buttonPlaying: $isPlaying}), that is, when initializing the variable modified with @Link$ , it needs to be modified.

For detailed code, see @Link official document

In fact, the above effects can also be achieved by using @Consume and @Provide , but the code needs to be modified, as follows:

insert image description here

To sum up, that is to say, when the developer needs to set up two-way synchronization for a variable (parent_a) of the parent component in the child component, the developer can use @State to decorate the variable (parent_a) in the parent component, and use @ in the child component Link decorates the corresponding variable (child_a). In this way, not only data synchronization between the parent component and a single child component can be realized, but also data synchronization between the parent component and multiple child components can be realized. As shown in the figure below, it can be seen that the parent-child component has set two-way synchronization for the variable of the ClassA type, then when the value of the attribute c of the variable in the child component 1 changes, the parent component will be notified of the synchronous change, and when the attribute c in the parent component changes When the value of is changed, all subcomponents will be notified of the synchronous change. ( Source of conclusion )

insert image description here

Reference materials:
HarmonyOS Hongmeng study notes (5) @State function description and simple case
@Link official document

Guess you like

Origin blog.csdn.net/chunqiuwei/article/details/127065275