3

我有这个“警报”组件:

@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":
    }
}
4

0 回答 0