[英]How can i create a blazor component?
我的警报类是
namespace RazorComponents.Models
{
public class Alert
{
public string Title { get; set; }
public string Text { get; set; }
public bool Dismissible { get; set; }
}
}
我的 AlertComponent 是
namespace RazorComponents.Test
{
public partial class AlertComponent : ComponentBase
{
public Alert Alert { get; set; }
}
}
有以下观点
@using Models
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>@Alert.Title</strong> You should check in on some of those fields below.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
返回编译时错误C# An object reference is required for the non-static field, method, or property
@Alert.Title
处C# An object reference is required for the non-static field, method, or property
这是正常的,但如何将 Alert 类作为视图中的模型传递?
至少在 MVC 中,我们可以选择@model Alert
并通过模型传递async Task<IViewComponentResult> InvokeAsync
您需要像这样向组件添加代码块:
@code
{
[Parameter]
private Alert Alert { get; set };
}
仅当您想从外部(从另一个组件)设置值时才添加 [Parameter] 属性。
您需要将[Parameter]
属性添加到Alert
属性中:
namespace RazorComponents.Test
{
public partial class AlertComponent : ComponentBase
{
[Parameter]
public Alert Alert { get; set; }
}
}
要使用您的组件,只需将您的警报作为参数传递,如下所示:
<AlertComponent Alert="Alert"/>
@code
{
public Alert Alert {get; set;}
}
定义类背后的代码:
public partial class AlertComponent
{
[Parameter]
public Alert Alert { get; set; }
[Parameter]
public EventCallback Close { get; set; }
}
你需要在这里: using Microsoft.AspNetCore.Components;
注意:EventCallback Close 参数用于调用打开警报的方法将其关闭。
定义 AlertComponent 的视图部分
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>@Alert.Title</strong> <div>@Alert.Text</div>
<button @onclick="@(() => Close.InvokeAsync())" type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@code {
}
用法:
@page "/"
@if (alert != null)
{
<AlertComponent Alert="alert" Close="Close" />
}
<button @onclick="ShowAlert">Display alert</button>
@code
{
private Alert alert;
private void ShowAlert()
{
alert = new Alert() { Title = "My alert", Text = "You are being alerted", Dismissible = true };
}
private void Close()
{
alert = null;
}
}
当您单击“显示警报”按钮时,会创建一个新的 Alert 实例,重新渲染 Page 组件,这次alert != null
为真,从而渲染了 AlertComponent。 当点击AlertComponent中的“关闭按钮”时,Index组件中定义的Close方法将alert变量的值设置为null,之后Index组件重新渲染,这次AlertComponent不会重新渲染因为警报变量的值为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.