Blazor-事件传参何时使用Lambda表达式

62 阅读1分钟

案例1

@page "/counter"
@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++;
        }
    }
}

案例2

<div @onclick="HandleDivClick">
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    <input value=@data @onkeypress="ProcessKeyPress" @onkeypress:preventDefault />
</div>

@code {
    private async Task HandleDivClick()
    {
        await JS.InvokeVoidAsync("alert", "Div click");
    }

    private async Task ProcessKeyPress(KeyboardEventArgs e)
    {
        // Omitted for brevity
    }

    private int currentCount = 0;

    private void IncrementCount(MouseEventArgs e)
    {
        // Omitted for brevity
    }
}

总结

  1. Blazor 默认不会自动传递额外参数,如果事件处理方法需要多个参数,就需要用 lambda 表达式 来手动传递。
  2. mouseEvent => HandleClick(mouseEvent, "Hello") 让我们既能接收 MouseEventArgs,又能传入 "Hello"
  3. 如果事件处理方法只需要 MouseEventArgs,就可以直接写 @onclick="HandleClick",不需要 lambda 表达式