Blazor 子父控件通信

5 篇文章 0 订阅
本文介绍了如何在Blazor中创建一个可复用的自定义文本框组件,支持字符计数和长度限制,并演示了如何在父组件中使用和传递数据。通过实例展示组件间的通信和数据共享,适合前端开发者深入理解Blazor组件开发。
摘要由CSDN通过智能技术生成

Introduction

Blazor is a new framework built by Microsoft for creating interactive client-side web UI with .NET codebase. We can write both client-side and server-side code in C#.NET itself. I have already written five articles about Blazor server on C# Corner. Please refer to below articles for more basics about Blazor framework.

Components are implemented in Razor component files (. razor) using a combination of C# and HTML mark-up. A component in Blazor is formally referred to as a Razor component.

We can create a child component and reuse in another component. We will share data between these components very easily. We will create a custom textbox as child component. This custom textbox will show the current character count in the textbox and will restrict the total number of characters, if needed. I will explain all the actions step by step.

Create Blazor application in Visual Studio 2019

We can define the html mark-up in the component.

  1. <div class="float-right">  
  2.     <i>Total Characters : @TextLength/@LengthString</i>  
  3. </div>  
  4.   
  5.    <div class="form-group row mb-2">  
  6.         <label class="col-md-3 col-form-label"  
  7.            for="Name">@FieldName</label>  
  8.         <div class="col-md7">  
  9.             <input class="form-control"  
  10.                    type="text"  
  11.                    placeholder="@FieldName" value="@Value" @οninput="OnValueChanged" maxlength="@MaxLength" />  
  12.         </div>  
  13.     </div>  

We can add the C# code also inside the @code block.

  1. @code {  
  2.        [Parameter]  
  3.        public string Value { get; set; }  
  4.   
  5.        [Parameter]  
  6.        public string FieldName { get; set; }  
  7.   
  8.        [Parameter]  
  9.        public int MaxLength { get; set; } = -1;  
  10.   
  11.        [Parameter]  
  12.        public EventCallback<string> ValueChanged { get; set; }  
  13.   
  14.        string LengthString;  
  15.        int TextLength;  
  16.   
  17.        protected override void OnInitialized()  
  18.        {  
  19.            TextLength = Value.Length;  
  20.            LengthString = (MaxLength == -1) ? "Unlimited" : MaxLength.ToString();  
  21.        }  
  22.   
  23.        private Task OnValueChanged(ChangeEventArgs e)  
  24.        {  
  25.            Value = e.Value.ToString();  
  26.            TextLength = Value.Length;  
  27.            return ValueChanged.InvokeAsync(Value);  
  28.        }  
  29.    }  

We have defined three parameters properties “Value”, “FieldName” and “MaxLength”.

FieldName is used for displaying field name and placeholder value in the custom textbox. MaxLength is used to restrict maximum characters limit in custom textbox, if needed. FieldName and MaxLength properties in Blazor act as @Input decorator in Angular. These properties are used to share data from parent component to child component. Value property acts as @Output decorator in Angular. This will be used for sharing data back from child component to parent component. In Angular, we use EventEmitter along with Output decorators to share data from child to parent component. In Blazor, we use “EventCallback” parameter to emit value from child component to parent component. Please note, “Changed” suffix is added to the value property parameter. This is the default convention used in Blazor.

We have created a “OnValueChanged” method and bind with “@oninput” attribute of input control in html mark-up.

CustomTextbox.razor

  1. <div class="float-right">  
  2.     <i>Total Characters : @TextLength/@LengthString</i>  
  3. </div>  
  4.   
  5.     <div class="form-group row mb-2">  
  6.         <label class="col-md-3 col-form-label"  
  7.            for="Name">@FieldName</label>  
  8.         <div class="col-md7">  
  9.             <input class="form-control"  
  10.                    type="text"  
  11.                    placeholder="@FieldName" value="@Value" @οninput="OnValueChanged" maxlength="@MaxLength" />  
  12.         </div>  
  13.     </div>  
  14.   
  15.     @code {  
  16.         [Parameter]  
  17.         public string Value { get; set; }  
  18.   
  19.         [Parameter]  
  20.         public string FieldName { get; set; }  
  21.   
  22.         [Parameter]  
  23.         public int MaxLength { get; set; } = -1;  
  24.   
  25.         [Parameter]  
  26.         public EventCallback<string> ValueChanged { get; set; }  
  27.   
  28.         string LengthString;  
  29.         int TextLength;  
  30.   
  31.         protected override void OnInitialized()  
  32.         {  
  33.             TextLength = Value.Length;  
  34.             LengthString = (MaxLength == -1) ? "Unlimited" : MaxLength.ToString();  
  35.         }  
  36.   
  37.         private Task OnValueChanged(ChangeEventArgs e)  
  38.         {  
  39.             Value = e.Value.ToString();  
  40.             TextLength = Value.Length;  
  41.             return ValueChanged.InvokeAsync(Value);  
  42.         }  
  43.     }  

We can add this child component inside a parent component. We can create new parent component.

ParentComponent.razor

  1. @page "/parentcomponent"  
  2.   
  3. <CustomTextbox @bind-Value="name" FieldName="Name" MaxLength="20" />  
  4. <CustomTextbox @bind-Value="address" FieldName="Address" />  
  5.   
  6. @code {  
  7.     string name = "Sarath Lal";  
  8.     string address = "Kakkanad";  
  9. }  

We have added two custom textbox child components inside this parent component. “@bind-{parametername}” is used for binding child component field with parent component field. Here, “Value” is the field name in the child component. So that, we used this as “@bind-Value”. We can pass these two input parameters “FieldName” and “MaxLength” from parent component. I have not passed MaxLength property for second child component. Hence, the default value -1 will be assigned to this component in run time.

We can modify the shared component “NavMenu” to add a navigation to parent component.

NavMenu.razor

  1. <div class="top-row pl-4 navbar navbar-dark">  
  2.     <a class="navbar-brand" href="">BlazorReusableComponent</a>  
  3.     <button class="navbar-toggler" @οnclick="ToggleNavMenu">  
  4.         <span class="navbar-toggler-icon"></span>  
  5.     </button>  
  6. </div>  
  7.   
  8. <div class="@NavMenuCssClass" @οnclick="ToggleNavMenu">  
  9.     <ul class="nav flex-column">  
  10.         <li class="nav-item px-3">  
  11.             <NavLink class="nav-link" href="" Match="NavLinkMatch.All">  
  12.                 <span class="oi oi-home" aria-hidden="true"></span> Home  
  13.             </NavLink>  
  14.         </li>  
  15.         <li class="nav-item px-3">  
  16.             <NavLink class="nav-link" href="counter">  
  17.                 <span class="oi oi-plus" aria-hidden="true"></span> Counter  
  18.             </NavLink>  
  19.         </li>  
  20.         <li class="nav-item px-3">  
  21.             <NavLink class="nav-link" href="fetchdata">  
  22.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data  
  23.             </NavLink>  
  24.         </li>  
  25.         <li class="nav-item px-3">  
  26.             <NavLink class="nav-link" href="parentcomponent">  
  27.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Parent Component  
  28.             </NavLink>  
  29.         </li>  
  30.     </ul>  
  31. </div>  
  32.   
  33. @code {  
  34.     bool collapseNavMenu = true;  
  35.   
  36.     string NavMenuCssClass => collapseNavMenu ? "collapse" : null;  
  37.   
  38.     void ToggleNavMenu()  
  39.     {  
  40.         collapseNavMenu = !collapseNavMenu;  
  41.     }  
  42. }  

We can run the application.

You can notice that, a new “Parent Component” link is appeared in the menu. You can click that link to see the parent component.

We have defined two custom textbox components inside the parent component. For the first textbox, we have given 20-character limit and for second component, no character limit is given. So that, you can enter unlimited characters in second textbox. The total characters count is also visible in the screen.

Conclusion

In this post, we have created a reusable child component in Blazor and easily used in another parent component. We have shared the data from parent component to child component and vice versa also.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值