问题
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