0

我试图跟进“捕获对元素的引用”以将更改从子组件传递给父组件,但它不起作用 url 是https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interop ?view=aspnetcore-3.0#capture-references-to-elements

请问可以帮我吗?a) 代码有什么问题吗?b)我可以在哪里找到“Console.WriteLine”信息,因为我无法从 vs 输出窗口找到它。

1. ParentComponent.razor

@page "/parentcomponent"
@using BlazorApp.Components

<h1>Parent Component</h1>

<p>ParentYear: @ParentYear</p>

<ChildComponent @ref="ChildComponent1" @bind-Year="ParentYear" />

@code {
    private int ParentYear = 1978;

    ChildComponent ChildComponent1 = new ChildComponent();

    protected override void OnInitialized()
    {
        ChildComponent1.YearChanged += ChildFiredEvent;
    }

    public void ChildFiredEvent(int _year)
    {
        ParentYear = _year;
        Console.WriteLine(ParentYear.ToString());
        StateHasChanged();
    }

}

2. Childcomponent.razor

<h2>Child Component</h2>

<p>ChildYear: @Year</p>

<button class="btn btn-primary" @onclick="ChangeTheYear">Change Year to 1986</button>

@code {
    [Parameter]
    public int Year { get; set; }

    [Parameter]
    public Action<int> YearChanged { get; set; }

    private void ChangeTheYear()
    {
        Year = 1986;
        YearChanged?.Invoke(Year);
    }
}
4

2 回答 2

1

非常感谢,萨默和大卫。我相信我使用了以前的 blazor 方法。现在它与@ref 一起工作得很好。干杯!!!这是代码。

@page "/parentcomponent"
@using BlazorApp.Components

<h1>Parent Component</h1>

<p>ParentYear: @ParentYear</p>

<ChildComponent @ref="ChildComponent1" @bind-Year="ParentYear" />

@code {
    private int ParentYear = 1978;

    ChildComponent ChildComponent1 = new ChildComponent();
}

<p>ChildYear: @Year</p>

<button class="btn btn-primary" @onclick="ChangeTheYear">Change Year to 1986</button>

@code {
    [Parameter]
    public int Year { get; set; }

    [Parameter]
    public Microsoft.AspNetCore.Components.EventCallback<int> YearChanged { get; set; }
    enter code here
    private void ChangeTheYear()
    {
        Year = 1986;
        YearChanged.InvokeAsync(Year);
    }
}
于 2019-10-04T13:13:43.770 回答
1

在子组件中,YearChanged 声明应如下所示:

public EventCallBack<int> YearChanged { get; set; }

然后你像这样调用它:

await YearChanged.InvokeAsync(newValue);
于 2019-10-04T12:28:47.833 回答