【问题标题】:Blazor InputText: conditionally rendering an attributeBlazor InputText:有条件地呈现属性
【发布时间】:2023-04-07 09:39:01
【问题描述】:

Blazor vRC1

我正在寻找一种简单的技术,用于在<InputText>(或任何输入组件)内有条件地呈现属性。这在 MVC Razor 中曾经很简单,您只需在 @(...) 语句中编写条件逻辑。现在,@(...) 在 Razor 语法中具有不同的含义。

例如,我想有条件地为InputText 输出autofocus HTML 属性。

<InputText 
 @bind-Value="@TextProperty"
 @(MyModel.isAutoFocus ? "autofocus" : "") <-  This is invalid razor syntax!
/>

【问题讨论】:

    标签: asp.net-core blazor blazor-server-side


    【解决方案1】:

    事实证明,如果属性的值为falsenull,Blazor 将不会呈现该属性

    https://docs.microsoft.com/en-us/aspnet/core/blazor/components?view=aspnetcore-3.0#conditional-html-element-attributes

    HTML 元素属性基于 .NET 有条件地呈现 价值。如果该值为 false 或 null,则不会呈现该属性。如果 值为真,属性呈现最小化。

    <InputText @bind-Value="@TextProperty" autofocus="@MyModel.isAutoFocus" />
    

    【讨论】:

    • 有趣的是——这也适用于disabledselected 标签,它们通常不等于任何东西。例如。 &lt;select @bind="selectValue" disabled="isDisabled"&gt;
    • @AlbatrossCafe 它不适用于disabled
    • 它也不适用于按钮的form 属性。
    • 适用于内置 InputText 组件的只读属性。
    【解决方案2】:

    这可以通过@attributes 标签实现。 See more here

    基本上,您可以将@attributes 标签添加到您的InputText。这可以绑定到一个参数,或者一个方便的小方法。

    <InputText @bind-Value="@TextProperty" @attributes="HandyFunction()" />
    
    @code{
        Dictionary<string,object> HandyFunction()
        {
            var dict = new Dictionary<string, object>();
            if(MyModel.isAutoFocus) dict.Add("autofocus",true);
            return dict;
        }
    }
    

    【讨论】:

    • 谢谢,虽然远没有 Razor 早期版本中应有的那么简单。
    • 如果您需要有条件地在 blazor 组件上设置参数,例如您需要传递渲染片段,这也适用。
    【解决方案3】:

    你可以试试下面的代码:

    <InputText  @bind-Value="@TextProperty"  autofocus="@(MyModel.isAutoFocus)"  />
    

    参考https://github.com/aspnet/AspNetCore/issues/10122

    【讨论】:

    • 自动对焦属性的存在启用了该功能。我需要有条件地写出属性,而不是值。
    • @Aaron Hudon 我试过发现如果设置autofocus= true,它会在页面的输入中显示为autofocus,如果autofocus= false,它不会显示为输入的属性.也许你可以打开浏览器F12查看结果?
    • 谢谢 - 我可能不得不退回到这个,但原来的问题仍然存在,如何有条件地输出属性。
    • @Aaron Hudon 我现在明白了,但我认为 blazor 还不支持。祝你好运......
    猜你喜欢
    • 2012-12-25
    • 2019-10-28
    • 2015-05-26
    • 2020-10-23
    • 2021-02-28
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多