我需要根据EventCallback<T>个异步调用的结果来调整子组件,从报告验证摘要中的错误开始.然而,我似乎找不到一种有效的方式来做到这一点,似乎交流完全是单向的,从子元素到父母.

我读到过一些答案,你可以用Func<T1, T2>代替EventCallback<T>,但它有一个严重的缺点,就是在需要的时候不打StateHasChanged().

    [Parameter]
    public EventCallback<int> OnAccountEntered { get; set; }

    private async Task HandleValidSubmit()
    {
        try
        {
            DisableButton = true;
            ButtonText = "Please Wait, Validating Account Information";
            await OnAccountEntered.InvokeAsync(Model.AccountNumber ?? 0).ConfigureAwait(false);
            
            // here be dragons. how do I get the answer from parent?
        }
        finally
        {
            ButtonText = "Request";
            DisableButton = false;
        }
    }

确保父对象和子对象之间双向通信的正确方式是什么?

推荐答案

使用Func名代表没有"严重的负面影响"或任何错误.您可以控制是否刷新父零部件.龙(就像 comments 一样)是虚构的.

这是一个使用Func<Task, int>的快速演示.

MyComponent

<div class="bg-light m-2 p-2">
    <h3>MyComponent</h3>
    <button class="btn btn-primary" @onclick=this.HandleValidSubmit>Update</button>
    <div class="bg-secondary text-white m-2 p-1">
        <pre>Counter: @counter </pre>
    </div>
</div>


@code {
    [Parameter] public Func<int, Task>? OnAccountEntered { get; set; }
    private int counter;

    private async Task HandleValidSubmit()
    {
        if (this.OnAccountEntered is not null)
        {
            // unless you're an async expert keep the await clean and simple
            await this.OnAccountEntered.Invoke(counter + 1);
            counter++;
            // put in a delay so you can see this component update afer the parent
            await Task.Delay(1000);
        }
    }
}

Index

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<div class="bg-dark text-white m-2 p-1">
    <pre>Counter: @counter </pre>
</div>

<MyComponent OnAccountEntered=this.AccountChanged />

@code{
    private int counter;

    private async Task AccountChanged(int value)
    {
        counter = value;
        // pretend we're an async method getting data from some async source
        await Task.Yield();
        // call StateHasChanged if the process mutates the state of this component
        StateHasChanged();
    }
}

Csharp相关问答推荐

C#中的两个线程之间读写浮点类型

.NET通过版本自动增量设置包版本

如果存在对CodeAnalysis.CSharp的引用,则不能引用netStandard2.0库

使用命令初始化可绑定属性

dotnet集合中内部数组的局部变量副本的用途是什么?'

Select Many和默认IfEmpty内部Select Many错误工作

在LINQ Where子句中使用新的DateTime

Thad.Sept()vs Task.Delay().Wait()

使用两个不同的枚举作为Switch语句中的CASE生成唯一值

C#Null判断处理失败

DateTime ToString()未以指定格式打印

TagHelpers在新区域不起作用

异步等待Foreach循环中的ConfigureAWait(FALSE)执行什么操作?

如何在.NET AOT中为所有枚举启用JsonStringEnumConverter

如何让两个.NET版本不兼容的项目对话?

在Windows Plesk上发布ASP.NET Core 7 Web API-错误:无法加载文件或程序集';Microsoft.Data.SqlClient';

如何允许数组接受多个类型?

RX操作员使用先前值进行扫描,信号来自值本身

如何将 colored颜色 转换为KnownColor名称?

在使用xUnit和Mock执行单元测试时,控制器ViewResult返回空的Model集合