• Blazor实现高级表单功能


    思路

    1. 添加Form组件类,提供Validate,OnSubmit等
    2. 添加Field组件基类,提供Id,Label,Value等
    3. 添加Field子组件Text、Password等表单字段组件
    4. 添加FormContext类,存储表单及字段数据
    5. 使用级联值组件传递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;
        }
    }
    
  • 相关阅读:
    细菌 状态压缩
    素数
    骑士问题(knight)
    魔法石的诱惑
    平面上的最接近点对
    救援行动(save)
    优先队列
    leetcode 92. 反转链表 II
    leetcode 91. 解码方法
    leetcode 39. 组合总和
  • 原文地址:https://www.cnblogs.com/known/p/16159525.html
Copyright © 2020-2023  润新知