Blazor實現(xiàn)高級表單功能
思路
添加Form組件類,提供Validate,OnSubmit等
添加Field組件基類,提供Id,Label,Value等
添加Field子組件Text、Password等表單字段組件
添加FormContext類,存儲表單及字段數(shù)據(jù)
使用級聯(lián)值組件傳遞FormContext實例(關鍵)
Form組件
public class FormContext {
? ?public Dictionary<string, Field> Fields { get; }
}
public class Form : BaseComponent {
? ?[Parameter] public RenderFragment ChildContent { get; set; }
? ?public FormContext Context { get; }
? ?public bool Validate() { return false; }
? ?
? ?protected override void BuildRenderTree(RenderTreeBuilder builder) {
? ? ? ?builder.Div(attr => {
? ? ? ? ? ?attr.Class(Style);
? ? ? ? ? ?builder.Component<CascadingValue<FormContext>>(attr => {
? ? ? ? ? ? ? ?attr.Add(nameof(CascadingValue<FormContext>.Value), Context);
? ? ? ? ? ? ? ?attr.Add(nameof(CascadingValue<FormContext>.ChildContent), ChildContent);
? ? ? ? ? ?});
? ? ? ?});
? ?}
}
Field組件
public class Field : BaseComponent {
? ?[Parameter] public string Id { get; set; }
? ?[Parameter] public string Label { get; set; }
? ?[CascadingParameter]
? ?protected FormContext Context { get; set; }
? ?protected override void OnInitialized() {
? ? ? ?base.OnInitialized();
? ? ? ?Context.Fields[Id] = this;
? ?}
? ?protected override void BuildRenderTree(RenderTreeBuilder builder) {
? ?}
? ?protected virtual void BuidChildContent(RenderTreeBuilder builder) {}
}
public class Text : Field {
? ?[Parameter] public string Icon { get; set; }
? ?[Parameter] public string Placeholder { get; set; }
? ?protected override void BuidChildContent(RenderTreeBuilder builder) {
? ?}
}
public class Password : Field {
? ?[Parameter] public string Icon { get; set; }
? ?[Parameter] public string Placeholder { get; set; }
? ?protected override void BuidChildContent(RenderTreeBuilder builder) {
? ?}
}
Form示例
<Form @ref="form">
? ?<Text Id="UserName" Icon="fa fa-user-o" Placeholder="用戶名" />
? ?<Password Id="Password" Icon="fa fa-lock" Placeholder="密碼" />
? ?<Button Text="登 錄" OnClick="OnLogin" />
</Form>
@code {
? ?private Form form;
? ?private void OnLogin() {
? ? ? ?if (!form.Validate())
? ? ? ? ? ?return;
? ?}
}
來源:https://www.dianjilingqu.com/203138.html