Blazor:如何将事件传递给通用组件中的onClick函数

时间:2019-12-28 19:54:45

标签: c# blazor

我正在为我正在制作的网站制作表格组件。我希望能够在一个页面上从表创建,更新,添加和删除条目。我还将在整个网站上使用此组件,并使用许多类作为输入。我去here学习如何做。我还认为,在表中的每一行中都有一个内部组件是很明智的。到目前为止,这是我的代码:

可编辑的类。剃刀

@using WbotV2.Data
@using System
@using System.Collections
@using System.Reflection
@typeparam TItem

    <tr>
        @foreach (var datum in Data)
        {
            <td>@datum</td>
        }
        <td><button class="btn btn-success">Edit</button></td>
        <td>@ChildContent</td>
    </tr>


@code {
    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter] 
    public TItem Item { get; set; }

    public List<string> Data;
    public bool Editable = false;
    protected override async Task OnInitializedAsync()
    {
        Data = GetData(Item);
    }

    public static List<string> GetData<T>(T instance)
    {
        List<string> ret = new List<string>();
        FieldInfo[] infos = typeof(T).GetFields();
        foreach (FieldInfo info in infos)
        {
            ret.Add(info.GetValue(instance).ToString());
        }
        return ret;
    }
}

该组件应允许我将类作为参数传递,然后编辑其字段。它还不应将用户带到单独的页面上进行编辑(如果可能,我希望将其内联在表中)。我的想法是使用绑定来执行此操作,但是类名是任意的,因此我不知道如何将其传递给@bind,这是我遇到的问题。

表Component.razor

@using WbotV2.Data
@using System
@using System.Collections
@using System.Reflection
@typeparam TItem

<table class="table">
    <thead>
        <tr>
            @foreach (string header in Headers)
            {
                <th>@header</th>   
            }
            <td>Edit</td>
            <td>Delete</td>
            <td><button class="btn btn-primary">Add</button></td>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Items)
        {
            <EditableClass Item="@item"><button class="btn btn-danger"  @onclick="(Delete(item))">Delete</button></EditableClass>
        }
    </tbody>
</table>


@code {
        [Parameter] 
        public IList<TItem> Items { get; set; }

        [Parameter] 
        public TableUtilityClass<TItem> DataInstance { get; set; }

    public string[] Headers;

    protected override async Task OnInitializedAsync()
    {
        Headers = GetHeaders();
    }

    public string[] GetHeaders()
    {
        List<string> ret = new List<string>();
        FieldInfo[] infos = typeof(TItem).GetFields();
        foreach (FieldInfo info in infos)
        {
            ret.Add(info.Name);
        }
        return ret.ToArray();
    }

    public void Delete(TItem itemToDelete)
    {
        DataInstance.Delete(itemToDelete);
        StateHasChanged();
        Console.WriteLine("Here");
    }

    public void Add(TItem itemToAdd)
    {
        DataInstance.Add(itemToAdd);
        StateHasChanged();
        Console.WriteLine("Here");
    }

    public List<List<string>> GetDataString<T>(IEnumerable<T> instance)
    {
        List<List<string>> ret = new List<List<string>>();
        foreach (T item in instance)
        {
            ret.Add(new List<string>());
            FieldInfo[] infos = typeof(T).GetFields();
            foreach (FieldInfo info in infos)
            {
                ret[ret.Count - 1].Add(info.GetValue(item).ToString());
                Console.WriteLine($"{info.Name}: {info.GetValue(item)}");
            }
        }
        return ret;
    }
}

此组件应在表中包含许多可编辑的类组件,并处理向其添加和删除的新条目。我当前的问题是删除,我尝试实现this solution,但在此行<EditableClass Item="@item"><button class="btn btn-danger" @onclick="(Delete(item))">Delete</button></EditableClass>上遇到了无法从void转换为Microsoft.AspNetCore.Components.EventCallback错误的问题,我也尝试了{{3 }}和this。我也想在这里提供一些帮助,或者解决错误,或者找到解决问题的巧妙方法。

Table Utility Class.cs

using System.Threading.Tasks;

namespace WbotV2.Data
{
    public abstract class TableUtilityClass<T>
    {
        public abstract Task Delete(T Item);
        public abstract Task Add(T Item);
    }
}

该类应该有助于简化与许多不同类型的服务的交互,正如我预期的那样。

最后,这是我的Countrys.razor(表格组件进入的页面)

@page "/countries"

@using WbotV2.Data
@inject WbotCountryService CountryService


<h1>Country Information</h1>


@if (countries == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <TableComponent Items="@countries" DataInstance="@CountryService"/>
}

@code {

    public List<WbotCountry> countries;

    protected override async Task OnInitializedAsync()
    {
        countries = await CountryService.GetCountriesAsync();
    }
}

对于那些想知道Country服务看起来像这样的人:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WbotV2.Data
{
    public class WbotCountryService : TableUtilityClass<WbotCountry>
    {
        public WbotData WbotDataInstance;

        public WbotCountryService()
        {
            WbotDataInstance = WbotData.LoadData();
        }
        public Task<List<WbotCountry>> GetCountriesAsync()
        {
            return Task.FromResult(WbotDataInstance.countries);
        }

        public override Task Delete(WbotCountry c)
        {
            WbotDataInstance.countries.Add(c);
            WbotDataInstance.SaveData();

            return Task.CompletedTask;
        }
        public override Task Add(WbotCountry c)
        {
            WbotDataInstance.countries.Remove(c);
            WbotDataInstance.SaveData();

            return Task.CompletedTask;
        }
    }
}

任何帮助都会得到帮助!

1 个答案:

答案 0 :(得分:1)

这有效:

EditableClass.razor

@using WbotV2.Data
@using System
@using System.Collections
@using System.Reflection
@typeparam TItem

<tr>
    @foreach (var datum in Data)
    {
        <td>@datum</td>
    }
    <td><button class="btn btn-success">Edit</button></td>
    <td>@ChildContent</td>
</tr>


@code {
    [Parameter]
    public RenderFragment ChildContent { get; set; }
    [Parameter]
    public EventCallback<TItem> Delete { get; set; }

    [Parameter]
    public TItem Item { get; set; }

    public List<string> Data;
    public bool Editable = false;
    protected override void OnInitialized()
    {
        Data = GetData(Item);
    }

    public static List<string> GetData(TItem instance)
    {
        List<string> ret = new List<string>();
        FieldInfo[] infos = typeof(TItem).GetFields(BindingFlags.NonPublic | BindingFlags.Instance
            | BindingFlags.Public);
        foreach (FieldInfo info in infos)
        {
            ret.Add(info.GetValue(instance).ToString());
        }
        return ret;
    }
}

请注意我所做的更改以及添加的代码。

TableComponent.razor

<EditableClass Item="@item"><button class="btn btn-danger" @onclick="@(() => Delete(item))">DeleteMe</button></EditableClass>


public void Delete(TItem itemToDelete)
    {
        DataInstance.Delete(itemToDelete);
      //  StateHasChanged();
       // Console.WriteLine("Here");
    }

还有其他问题,但是现在,我没有时间。我将尝试进一步改善它。该服务可以向您展示如何创建服务以及如何与组件通信:https://github.com/aspnet/samples/blob/master/samples/aspnetcore/blazor/FlightFinder/FlightFinder.Client/Services/AppState.cs

希望这对您有帮助...