You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server端使用InvokeVoidAsync时CSS元素类泄露问题

问题描述

我尝试实现类似Vue/React的表格行删除过渡效果,逻辑是通过Blazor的InvokeVoidAsync调用JS函数给目标行添加CSS类执行淡出动画,JS中用sleep延迟执行,打算等动画结束后再让服务器端删除对应项。但实际运行时出现问题:服务器删除项后,原本要应用到被删除行的动画类,会错误地被应用到下方的行上,导致动画错位。

实现代码

Index.razor

@page "/"

<h2> @Pizzas.Count() 份披萨</h2>

<table class="table">
    <thead>
        <tr>
            <th>名称</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var pizza in Pizzas)
        {
            <tr id="@(pizza.ID)">
                <td>@pizza.Name</td>
                <td><button @onclick="@(async _ => await RemovePizza(pizza))">删除</button></td>
            </tr>
        }
    </tbody>
</table>
@inject IJSRuntime JSRuntime
@code {
    public record Pizza(Guid ID, string Name);
    public string[] PizzaTypes => new[] { "意大利辣香肠", "芝士", "夏威夷", "素食", "培根", "西南烧烤", "芝士汉堡", "水牛城", "肉食", "至尊" };

    public List<Pizza> Pizzas { get; set; } = new();

    protected override void OnInitialized()
    {
        base.OnInitialized();
        try
        {
            for (int i = 0; i < 10; i++)
                AddPizza();

        }
        catch (Exception)
        {

            throw;
        }
        StateHasChanged();
    }

    public void AddPizza()
    {
        Pizzas.Add(new Pizza(Guid.NewGuid(), PizzaTypes[new Random().Next(0, PizzaTypes.Length - 1)]));
    }
    public async Task RemovePizza(Pizza pizza)
    {
        await JSRuntime.InvokeVoidAsync("animateTransition", pizza.ID, "fade-away", 1000);
        Pizzas.Remove(pizza);
    }
}

JavaScript 函数

var sleep = async (ms) => new Promise(resolve => setTimeout(resolve, ms));

var animateTransition = async (id, className, duration) => {
    const el = document.getElementById(id);
    el.classList.add(className);
    await sleep(duration);
};

CSS 样式

@keyframes fadeOut {
    from {
        opacity: 1;
    }

    to {
        opacity: 0;
    }
}

tr.fade-away {
    animation-name: fadeOut;
    animation-duration: 1s;
}

内容的提问来源于stack exchange,提问作者cseguin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 05:50:11