我有这个“警报”组件:
@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();
}
}
关于c# - 组件中的调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53133647/