且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Blazor Server 应用程序中停止事件传播

更新时间:2023-02-06 22:52:16

如果它有帮助,并添加到@Ivan 为似乎对我不起作用的 MatBlazor MatButton/MatIconButton 所做的评论中,我使用了以下解决方法:

<MatButton OnClick="@DoSomething";@ref=MyButton">做吧!</MatButton>

我需要同时使用 stopPropagation 和 preventDefault.我不得不使用 div 包装器,因为 MatButton 不允许我添加多个点击.

I'm using Grid.Blazor library to render server side grid on Blazor app. One of the column has a button with click event. So when button is clicked then grid row event is also fired along with button click event. I want to stop event propagation and only let button click event fired.

Grid:

  <GridComponent @ref="_gridComponent" T="QuickLists" Grid="@_grid"  OnRowClicked="@(async (item) => await ExerciseDetails(item))"></GridComponent>


Action<IGridColumnCollection<QuickExcerciseLists>> columns = c =>
        {
            c.Add().Titled("Actions").RenderComponentAs(typeof(ChildComponent)).SetWidth("5%");
            c.Add(o => o.Name, comparer).Titled("Name").SetWidth("10%");
            c.Add(o => o.Age, comparer).Titled("Age").SetWidth("15%");
            c.Add(o => o.Address, comparer).Titled("Address").RenderComponentAs<MatTooltip>().SetWidth("15%");
        };

Custom Column Component :

<MatBlazor.MatButton Icon="@MatIconNames.Remove_red_eye" @onclick="@ShowData" @onclick:stopPropagation="true"></MatBlazor.MatButton>

I tried passing @onclick:stopPropagation in the child button component. But it's given below compile error.

The component parameter 'onclick' is used two or more times for this component. Parameters must be unique (case-insensitive). The component parameter 'onclick' is generated by the '@onclick:stopPropagation' directive attribute.

I'm running .Net core 3.1.201. Any help is highly appreciated.

In case it helps, and to add to the comment @Ivan made for the MatBlazor MatButton/MatIconButton which didn't seem to work for me, I used the following workaround:

<div @onclick:stopPropagation="true" @onclick:preventDefault="true">
  <MatButton OnClick="@DoSomething" @ref="MyButton">Do it!</MatButton>
</div>

I needed to use both stopPropagation and preventDefault. I had to use the div wrapper as MatButton didn't allow me to add multiple onclicks.