Blazor 服务器 - 如何禁用组件内的控件?

Blazor Server - How to disable a control inside component?

我尝试通过在组件(预隐藏)中添加“禁用”class 来显示和禁用按钮,但失败了 - 它不起作用。我哪里做错了?

组件按钮:

<div class="form-group">
    <button class="btn btn-primary @disabled">Disable Me</button>
</div>

@code {
    string _password;
    string disabled = "";

    public void Disable()
    {
        disabled = "disabled";
    }
}

Index.razor :

@page "/"

<h1>How to disable button in component ?</h1>

<button class="btn btn-primary" @onclick="ShowAndDisableButton">Show and disable button</button>

@if (show)
{
    <ButtonComponent @ref="button"/>
}

@code
{
    ButtonComponent button = new();
    bool show = false;

    void ShowAndDisableButton()
    {
        show = true;
        button.Disable();
    }
}

更新:如果我将 ShowAndDisableButton 代码更改为

async Task ShowAndDisableButton()
{
    show = true;
    await Task.Delay(TimeSpan.FromMilliseconds(10)); // add this, wait for a while
    button.Disable();
}

并将index.razor中的按钮代码更改为

<button class="btn btn-primary" @onclick="()=>ShowAndDisableButton()">Show and disable button</button>

有效。但是我不知道为什么也不想这样用,请问有什么好的方法吗?

使用 disabled="@disabledState" 其中 disabledState 是布尔值

问题是button.Disable();不会导致正常的重新渲染。

而且这是一种过于复杂的做事方式。

在页面中:

@if (show)
{
    <ButtonComponent Disabled="!show" />
}

@code
{
    //ButtonComponent button = new();
    bool show = false;

    void ShowAndDisableButton()
    {
        show = true;
        //button.Disable();
    }
}

和按钮本身:

<div class="form-group">
    <button class="btn btn-primary" disabled="Disabled">Disable Me</button>
</div>

@code {
    string _password;
//    string disabled = "";

    [Parameter] public bool Disabled {get; set; }
 
}

但是您将无法使用此按钮。