ElementReference 对 Blazor 中条件创建的元素的引用

Sou*_*uke 6 c# asp.net blazor blazor-webassembly

我正在尝试将焦点设置为有条件呈现的输入控件。我正在设置ElementReference,但它的 id 和 context 都为空。

<button @onclick="ToggleInput">Show input</button>
@if(showInput) {
    <input @ref="inputRef" type="text"/>
}

@code {
    private ElementReference inputRef;
    private bool showInput;

    async void ToggleInput() {
        showInput = !showInput;

        await inputRef.FocusAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我按下按钮时,它在控制台中显示此错误:

System.InvalidOperationException:ElementReference 尚未正确配置

完整错误消息:

在此输入图像描述

出现错误的工作示例https://blazorrepl.com/repl/wbueaMPK28hf2NNv09

Nik*_*696 8

这似乎有效,并且不必是一个单独的组件。我把它贴在起始页上。

<button @onclick="ToggleInput">Show input</button>
@if (showInput)
{
    <input @ref="inputRef" type="text" />
}

@code {
    private ElementReference inputRef;
    private bool showInput;

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (showInput) await inputRef.FocusAsync();
    }

    void ToggleInput()
    {
        showInput = !showInput;
    }
}
Run Code Online (Sandbox Code Playgroud)