Blazor链接-如果有onclick方法,请禁用href [英] Blazor link - disable href if there's an onclick method
问题描述
在Blazor中,我有一个同时具有href
和onclick
方法的<a>
元素:
In Blazor I have an <a>
element that has both a href
and an onclick
method:
<a href="" onclick="@(() => ChangePage(_someObject))">Test</a>
onclick
调用此方法:
private bool ChangePage(object objectToDisplay)
{
_currentObject = objectToDisplay;
StateHasChanged();
return false;
}
通常在JavaScript中,事件方法在href
中停止对链接的后续导航,但返回false似乎与上面的代码不兼容.
Normally in JavaScript returning false from the event method stops the subsequent navigation to the link in the href
but this doesn't seem to be working with my code above.
单击链接后,如何停止Blazor将页面更改为根URL?
How can I stop Blazor changing the page to the root url after the link is clicked?
(最明显的答案是完全删除href
,但是我正在使用Bootstrap药丸中的链接,而删除href
会使药丸停止工作)
(The obvious answer here would be to remove the href
altogether, but I'm using the link in a bootstrap Pill and removing the href
stops the Pills working)
- 将
<a>
元素更改为一个跨度并设置data-target
属性,但这将使Pills正常渲染. - 将
return
添加到onclick
事件中(根据此答案):onclick="return @(() => ChangePage(_overviewModel))"
但这没有不会编译. - 在
onclick
事件之后添加return
:onclick="@(() => ChangePage(_overviewModel)); return false;"
,但这也不编译. - 使用Blazor
NavLink
组件<NavLink href="" onclick="@(() => ChangePage(_someObject))">NavLink</NavLink>
- Changing the
<a>
element to a span and setting thedata-target
attribute, but that stops the Pills rendering properly. - Adding
return
into theonclick
event (as per this answer):onclick="return @(() => ChangePage(_overviewModel))"
but that doesn't compile. - Adding
return
after theonclick
event:onclick="@(() => ChangePage(_overviewModel)); return false;"
but that doesn't compile either. - using a Blazor
NavLink
component<NavLink href="" onclick="@(() => ChangePage(_someObject))">NavLink</NavLink>
推荐答案
这篇关于Blazor链接-如果有onclick方法,请禁用href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!