Blazor-事件参数用法

88 阅读1分钟

案例

@inject IJSRuntime JS

<h1>Counter</h1>

<p id="currentCount">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick='mouseEvent => HandleClick(mouseEvent, "Hello")'>Click me</button>

@code {
    private int currentCount = 0;

    private async Task HandleClick(MouseEventArgs e, string msg)
    {
        if (e.CtrlKey) // Ctrl key pressed as well
        {
            await JS.InvokeVoidAsync("alert", msg);
            currentCount += 5;
        }
        else
        {
            currentCount++;
        }
    }
}

执行逻辑

用户点击按钮

Blazor 生成 MouseEventArgs 对象

Lambda 表达式捕获事件对象 → 传递 mouseEvent + "Hello"

HandleClick 方法处理业务逻辑
├─ 调用 JS 交互(需 Ctrl 键)
└─ 更新组件状态(currentCount

Blazor 自动触发 UI 重渲染