c# - 组件中的调用方法

标签 c# .net-core blazor

我有这个“警报”组件:

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

最佳答案

要调用组件方法,请尝试使用 @ref 添加对组件的引用,然后在 @code block 中添加组件声明。如果这些方法在组件中是公共(public)的,您可以在组件范围之外使用它们。

Parent.razor

<Alert @ref="Alert" Text="I am showing" /> @*Notice the @ref tag;*@
<button @onclick="() => ShowAlert(true)">Show Success</button>
<button @onclick="() => ShowAlert(false)">Show Failure</button>
<button @onclick="HideAlert">Hide</button>

@code {
    private Alert Alert { get; set; } // This is where the @ref is bound; no need to initialize, the markup does that for you.

    private void ShowAlert(bool success)
    {
        if (success) Alert.ShowSuccessMessage("Success!!");
        else Alert.ShowErrorMessage("Failed :(");
    }
    private void HideAlert() => Alert.Hide();
}

Alert.razor

@if (_show)
{
    <div class="alert alert-@_class" role="alert">
        <strong>@Text</strong>
    </div>
}

@code
{
    [Parameter] public string Text { get; set; } = string.Empty; // set as "I am showing", but will be updated if a message is passed to the show methods below

    private bool _show { get; set; }
    private string _class { get; set; } = string.Empty;

    public void Hide() { _show = false; StateHasChanged(); }

    public void ShowSuccessMessage(string message? = null)
    {
        _show = true;
        Text = message ?? Text ?? string.Empty;
        _class = "success";
        StateHasChanged(); // StateHasChanged() informs the parent component that the child has updated and to update the dom
    }

    public void ShowErrorMessage(string? message = null)
    {
        _show = true;
        Text = message ?? Text ?? string.Empty;
        _class = "danger";
        StateHasChanged();
    }
}

参见部分: Capture references to components

关于c# - 组件中的调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53133647/

相关文章:

forms - 如何实时显示/隐藏元素(Blazor)?

c# - Visual Studio 找不到 Microsoft.AspNetCore.DataProtection 的 PersistKeysToRedis 方法

linux - Linux docker:System.Security.Authentication.AuthenticationException:根据验证过程,远程证书无效

c# - 在 Blazor WebAssembly 应用程序上加载请求 B2C 登录屏幕时出错

c# - C# 中的舍入函数

c# - 为什么客户端 Blazor 使用 .NET Standard 2.0 以及如何将 .NET Core 3.0 与 Blazor 一起使用?

c# - 如何通过代码测试某些条件然后验证或无效并显示错误消息?

c# - 来自内存中资源的 MSBuild

c# - Visual Studio调试器在混合 Debug模式下停止击中断点

c# - 无法从根提供程序解析范围服务 'Microsoft.AspNetCore.Identity.UserManager` 1[IdentityServerSample.Models.ApplicationUser]'