为什么 blazor 渲染两次?

时间:2021-03-25 13:32:51

标签: c# .net blazor blazor-webassembly blazor-client-side

我正在开发一个基本的 blazor webassembly 项目。一切都很顺利,直到我遇到这种情况。项目有效但渲染两次。

项目是关于分页的,快点,我想向你展示我的相关课程。

ThList.razor:

@foreach (var item in List)
{
    <Th @bind-Name="item.Name" @bind-Class="item.Class" @bind-IsCurrent="item.IsCurrent" OnClick="OnClick"></Th>
}

@code {

    [Parameter]
    public IList<Th> List { get; set; }

    [Parameter]
    public EventCallback<IList<Th>> ListChanged { get; set; }

    public void OnClick(Th th)
    {
        foreach (var item in List)
        {
            item.IsCurrent = item.Name == th.Name;
            item.SetClass();
            (item.Name + " " + item.IsCurrent).ToConsole();
        }
    }
}

Th.razor:

<th @attributes="InputAttributes" class="@Class" @onclick="(()=>OnClick.InvokeAsync(this))">@Name</th>

@code{
    private readonly string _defaultClass = "sorting";

    private bool _IsCurrent;

    [Parameter]
    public string Name { get; set; }

    [Parameter]
    public string Class { get; set; }

    [Parameter]
    public bool IsCurrent
    {
        get { return _IsCurrent; }
        set
        {
            _IsCurrent = value;
        }
    }

    [Parameter]
    public EventCallback<bool> IsCurrentChanged { get; set; }

    [Parameter]
    public EventCallback<string> NameChanged { get; set; }

    [Parameter]
    public EventCallback<string> ClassChanged { get; set; }

    [Parameter]
    public EventCallback<Th> OnClick { get; set; }

    public void SetClass()
    {
        if (IsCurrent) $"{Name}: here is setclass".ToConsole();
        if(IsCurrent)
            if (String.IsNullOrEmpty(Class))
                Class = $"{_defaultClass}_asc";
            else
                Class = Class.Contains("asc") ? Class.Replace("asc", "desc") : Class.Replace("desc", "asc");
        else
            Class = _defaultClass;
    }

    private Dictionary<string, object> InputAttributes { get; set; } = new Dictionary<string, object>()
    {
        { "tabindex", "0" },
        { "rowspan", "1" },
        { "colspan", "1" },
        { "style", "width: 14px;"}
    };
}

DataTables.razor:

***
        <thead>
            <tr role="row">
                <ThList @bind-List="ThList"></ThList>
            </tr>
        </thead>
***
@code {
    IList<Th> ThList = new List<Th>()
    {
        new Th(){Name = "Id", IsCurrent = true},
        new Th(){Name = "Name"},
        new Th(){Name = "Surname"},
        new Th(){Name = "Email"},
        new Th(){Name = "Gender"}
    };

    IList<PaginateButton> paginateButtonList = new List<PaginateButton>()
    {
        new PaginateButton(){Name = "1", IsCurrent = true},
        new PaginateButton(){Name = "2"},
        new PaginateButton(){Name = "3"}
    };

    DataTablesRequest dataTablesRequestModel = new DataTablesRequest();
}

注意:我读了microsoft documentation,但我无法完全理解。我是 Blazor 的新手。请有人向我解释并告诉我方法。

0 个答案:

没有答案