How to prevent default navigation for Blazor NavLink component

会有一股神秘感。 提交于 2020-03-24 14:19:56

问题


Since Blazor 3.1 Preview 2 it should be possible to prevent default navigation behaviour for links in Blazor, as also discussed in this answer.

However, this code:

<NavLink href="" Match="Match" @onclick:preventDefault @onclick="()=>LinkAction()" >
Do something
</NavLink>

gives this error:

The component parameter 'onclick' is used two or more times for this component. Parameters must be unique (case-insensitive)

Why is that?


回答1:


Although the net result of the HTML <A> tag and the Blazor NavLink component is the roughly the same thing, the @onclick:preventDefault syntax only works for the HTML version, not on Blazor components.

Steve Sanderson explains this here:

I'm afraid there isn't a mechanism for passing through arbitrary directive attributes such as @*:preventDefault as component parameters, so this isn't expected to work on NavLink.

Steve also gives a possible solution:

However, you could inherit your own subclass from NavLink that adds the "prevent default" behavior. For example, create NavLinkPreventDefault.razor, containing this:

@inherits NavLink 
<a @attributes="@AdditionalAttributes" class="@CssClass" @onclick:preventDefault>
    @ChildContent 
</a> 

Now you can use instead of to get the behavior you want.



来源:https://stackoverflow.com/questions/60653318/how-to-prevent-default-navigation-for-blazor-navlink-component

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!