我正在尝试使用复选框系统生成自己的组件,以了解是否需要该属性(类型为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 />
因为我的组件上将有很多属性,所以我想使其更简单
您不能在此属性之前使用此子句@if(isMintInt == true ? Min="@MinInt" : String.Empty
,就像这样:
MyXXX =“ @(if(isMintInt == true?Min =” @ MinInt“:String.Empty)”]
我的组件上将有很多属性,我想简化一下
您不能直接这样做。但是,作为一种变通方法,可以使用@attributes
动态绑定属性。例如:
<MyComponent @bind-Value="ValueInt" @attributes="@a_dictionary_expression" />
其中@a_dictionary_expression
是C#表达式,可以在运行时对其求值。而且,您甚至可以创建一个自定义函数来计算字典:
<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 ;
}
}