如何编写自定义ElementReference聚焦并避免JSInterop分配?

解读

在 Blazor 中,官方只提供了 FocusAsync 扩展方法,底层仍然通过 JSInterop 完成聚焦。
国内面试官问“避免 JSInterop 分配”并不是让你完全不用 JS,而是考察两点:

  1. 能否把 JS 代码“静态化”——只加载一次、不反复 new Function,从而消灭每次聚焦时的字符串/委托分配;
  2. 能否把逻辑封装成可复用的 C# 组件,让业务层零 JS 感知。
    如果能给出“一次注入、多次复用、零托管-JS 往返”的方案,就能体现你对 Blazor 渲染管线与浏览器 API 的深度理解。

知识点

  • ElementReference 与 DOM 句柄的生命周期
  • IJSRuntime 的同步/异步调用开销与字符串缓存策略
  • 自定义 JS 模块的“静态注册”机制(JS Isolation)
  • 组件基类与扩展方法对 ElementReference 的封装技巧
  • 浏览器 focus()、activeElement、focus-options 的兼容性差异
  • 性能计数:GC 分配、WASM-JS 往返、渲染队列重入

答案

  1. 定义静态 JS 模块
    在 wwwroot 下新建 focusHelper.js,只导出一个函数:

    export function focusElement(elem, preventScroll) {
        if (elem && typeof elem.focus === 'function') {
            elem.focus({ preventScroll: !!preventScroll });
        }
    }
    
  2. 在 Program.cs 中一次性注册模块

    builder.Services.AddScoped<FocusHelper>();
    
  3. 封装 C# 端服务,模块只加载一次并缓存

    public sealed class FocusHelper : IAsyncDisposable
    {
        private readonly IJSRuntime _js;
        private IJSObjectReference? _mod;
    
        public FocusHelper(IJSRuntime js) => _js = js;
    
        public async ValueTask FocusAsync(ElementReference el, bool preventScroll = false)
        {
            _mod ??= await _js.InvokeAsync<IJSObjectReference>(
                "import", "./focusHelper.js");
            await _mod.InvokeVoidAsync("focusElement", el, preventScroll);
        }
    
        public async ValueTask DisposeAsync()
        {
            if (_mod is not null) await _mod.DisposeAsync();
        }
    }
    
  4. 给组件层提供零 GC 扩展方法

    public static class ElementReferenceExtensions
    {
        public static Task FocusNoAlloc(this ElementReference el,
            bool preventScroll = false)
        {
            // 从 DI 直接取单例服务,不 new 委托,不拼接字符串
            var helper = 
                (IJSInProcessRuntime?)null!; // 仅示意,实际从 scoped 取
            return helper.FocusAsync(el, preventScroll);
        }
    }
    
  5. 业务代码一行调用

    <input @ref="txt" />
    @code{
        ElementReference txt;
        [Inject] FocusHelper Focus { get; set; }
        protected override async Task OnAfterRenderAsync(bool first)
        {
            if (first) await Focus.FocusAsync(txt);
        }
    }
    

结果:

  • JS 模块仅加载一次,后续聚焦无字符串分配;
  • 无内联 @onclick="async () => await JS.InvokeAsync..." 的匿名委托;
  • 完全可单元测试,且符合国内企业对“高性能 Blazor” 的考核点。

拓展思考

  1. 如果运行环境是 Blazor Server,网络延迟成为主要矛盾,可进一步把“聚焦指令”合并到同一批渲染的 JS 队列,减少一次 SignalR 往返。
  2. 对于 Unity WebGL 或 MAUI Blazor Hybrid,可判断运行时类型,在 WASM 下走模块方案,在 Hybrid 下直接调用平台 API,彻底摆脱 JS。
  3. 可扩展为“焦点陷阱”组件,用同一套静态 JS 管理 Tab 顺序与焦点循环,满足国内金融、政务系统对无障碍的强合规要求。