blazor中不是布尔值的条件属性

问题描述 投票:0回答:2

我正在尝试使用复选框系统生成自己的组件,以了解是否需要该属性(类型为int / float等)

<input type="checkbox" @bind="isMinInt" />
@if (isMinInt == true) {
    <input type="number" @bind="MinInt"/>
}

Si,我想替换这个@if

@if(isMinInt == true) {
    <MyComponent @bind-Value="ValueInt" Min="@MinInt"/>
} else {
    <MyComponent @bind-Value="ValueInt"/>
}

通过类似

<MyComponent @bind-Value="ValueInt" 
             @if(isMinInt == true ? Min="@MinInt" : String.Empty />

因为我的组件上将有很多属性,所以我想使其更简单

asp.net-core blazor
2个回答
0
投票

您不能在此属性之前使用此子句@if(isMintInt == true ? Min="@MinInt" : String.Empty,就像这样:

MyXXX =“ @(if(isMintInt == true?Min =” @ MinInt“:String.Empty)”]


0
投票

我的组件上将有很多属性,我想简化一下

您不能直接这样做。但是,作为一种变通方法,可以使用@attributes动态绑定属性。例如:

<MyComponent @bind-Value="ValueInt" @attributes="@a_dictionary_expression"  />

其中@a_dictionary_expressionC#表达式,可以在运行时对其求值。而且,您甚至可以创建一个自定义函数来计算字典:

<MyComponent @bind-Value="ValueInt" @attributes="getAttributes()"  />

@code {
    ... 
    private IDictionary<string, object> getAttributes()
    {
        var dict = new Dictionary<string, object>(){};
        if(isMinInt) {
            dict.Add("Min", $"{MinInt}");
        }
        return dict ;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.