我有这个“警报”组件:
@if (Show)
{
<div class="alert @Class" role="alert">
@Text
</div>
}
@functions
{
[Parameter]
private bool Show { get; set; } = false;
[Parameter]
private string Text { get; set; } = String.Empty;
[Parameter]
private string Class { get; set; } = String.Empty; //Success, Warning etc.
}
但是,当我在页面上调用此组件时,我仍然需要创建至少两个变量-ShowError和ErrorText-处理此警报的状态仍然使我的代码很混乱,因为该警报实际上存在于所有页面上。>
我的问题是:是否可以通过在子组件中调用ShowMessage方法来使代码混乱?
一个例子就是这样:
页面
@page "/my-page"
@inject HttpClient Http
<!-- A lot of HTML code here -->
<Alert/>
<!-- A lot of HTML code here -->
@functions {
protected override async Task OnInitAsync()
{
var response = await Http.PostJsonAsync<Response>("/api/sessions/create", null);
if (response.StatusCode == HttpStatusCode.OK)
{
}
else
{
myAlertComponent.ShowSuccessMessage(response.Message);
}
}
}
“警报”组件
@if (Show)
{
<div class="alert @Class" role="alert">
@Text
</div>
}
@functions
{
[Parameter]
private bool Show { get; set; } = false;
[Parameter]
private string Text { get; set; } = String.Empty;
[Parameter]
private string Class { get; set; } = String.Empty; //Success, Warning, Danger
public void HideAlerts()
{
Show = false;
}
public void ShowSuccessMessage(string message)
{
Show = true;
Text = message;
Class = "success":
}
public void ShowErrorMessage(string message)
{
Show = true;
Text = message;
Class = "danger":
}
}
答案 0 :(得分:1)
这是.NET(在本例中为Blazor)中组件之间的通信方式...
定义一个Action委托,该委托封装一个具有单个参数的方法
public event Action<string> DisplayAlert;
protected override async Task OnInitAsync()
{
var response = await Http.PostJsonAsync<Response> ("/api/sessions/create", null);
if (response.StatusCode == HttpStatusCode.OK)
{
// Success should be here, I believe
NotifyStateChanged(response.Message);
}
else
{
}
}
//Invoke any methods added to the event delegate:
private void NotifyStateChanged(string message) => DisplayAlert?.Invoke(message);
这: 将对ShowSuccessMessage方法的引用分配给在父组件中定义的DisplayAlert委托的实例。
<Alert DisplayAlert = "@( str => ShowSuccessMessage(str))/>
<!-- A lot of HTML code here -->
-------------------------------------------------------------------------------
"Alert" component
----------------
Define a method whose signature corresponds to that defined by the delegate
private static void ShowSuccessMessage(string message)
{
Show = true;
Text = message;
Class = "success":
}
希望这对您有帮助...