Question
After the long-press menu is configured for component A by bindContextMenu, when clicking an area outside the menu, event passthrough occurs, resulting in that component A responds to the click event. This does not meet the design requirements in some scenarios. The event transfer to lower-layer components needs to be completely blocked when a menu is displayed.
Solution
Currently, the default modal behavior of the menu is that only the area in the menu is interactive, while the area outside the menu keeps event penetration (clicking will penetrate to the lower-layer component), and the enumeration value corresponding to the default modal mode (for example, ModalMode.NONE). Since API version 20, HarmonyOS has opened up the configuration capability for the menu modal mode. You can just set ModalMode to TARGET_WINDOW.
Example:
@Entry
@Component
struct ModalModeDemo {
@State btnMessage: string = "Click To Trigger, longPress To Pop Up Menu"
@State toastMessage: string = "The Click event was triggered."
@Builder
MyMenu() {
Menu() {
MenuItem({ content: "MenuOptionOne" })
MenuItem({ content: "MenuOptionTwo" })
}
}
build() {
Stack({ alignContent: Alignment.Center }) {
Column() {
Flex({ justifyContent: FlexAlign.SpaceAround, alignItems: ItemAlign.Center }) {
Column() {
Button(this.btnMessage)
.bindContextMenu(this.MyMenu, ResponseType.LongPress, {
modalMode: ModalMode.TARGET_WINDOW,
placement: Placement.BottomLeft
})
.onClick(() => {
this.getUIContext().getPromptAction().showToast({
message: this.toastMessage
})
})
}
}
}
}.width('100%').height('100%')
}
} Reference