我试图跟进“捕获对元素的引用”以将更改从子组件传递给父组件,但它不起作用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);
}
}
答案 0 :(得分:1)
非常感谢您,Samer和David。我相信我以前使用过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);
}
}
答案 1 :(得分:0)
在子组件中,YearChanged声明应如下所示:
public EventCallBack<int> YearChanged { get; set; }
然后像这样调用它:
await YearChanged.InvokeAsync(newValue);