Blazor 新手,在添加内联 html 时遇到问题。
我正在尝试更新一个旧的实践解决方案,这就是我所拥有的:
<a href="#" @(Model.SideNavHasTooltips ? "tooltip=" + @item.Name + " flow=right" : string.Empty)>
那会产生类似的东西
<a href="#" tooltip="abc" flow="right">
使用 Blazor,我在执行此操作时遇到了更多困难,并且不确定我是否遗漏了一些明显的东西?
<div @(SideNavHasTooltips ? "tooltip=" + @item.Name + " flow=right" : string.Empty)>
我试过将它添加到一个变量并使用它,并尝试了一些其他的想法,但都无济于事。
我真的不确定这样做的正确方法是什么,但它不一样,所以任何建议都会有所帮助。
谢谢
最佳答案
您可以使用 Attribute splatting and arbitrary parameters使用 @attributes
参数。
<div @attributes="@TooltipAttributes(item.Name)"></div>
在您的代码中,您需要一个方法,例如:
IDictionary<string, object> TooltipAttributes(string itemName)
{
return SideNavHasTooltips
? new Dictionary<string, object>()
{{ "tooltip", itemName }, {"flow","right"}}
: new Dictionary<string, object>() { };
}
这将生成标签:
<div tooltip="the_name_you_gave_it" flow="right"></div>
或者如果SideNavHasToolTips
是false
<div></div>
@attributes
接受字符串、对象的字典。
或者你可以内联:
<div @attributes="@( SideNavHasToolTips ? new Dictionary<string, object> { {"tooltip", item.Name},{"flow","right"} } : new Dictionary<string, object> { } )"></div>
关于c# - 如何使用 Blazor c# 添加内联 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63583180/