[英]How to pass data from child component to parent
I can't seem to find any answer for this question but it seems simple enough to exist.我似乎找不到这个问题的任何答案,但它似乎很简单,可以存在。 Basically I want to send data from Child component to Parent.
基本上我想将数据从子组件发送到父组件。
Here is an example of Child component Cars
下面是一个子组件
Cars
的例子
@using Newtonsoft.Json
@if(ReponseCarsJSON) {
@foreach (var car in ReponseCarsJSON) {
<p @onclick="() => onSelectCar(car.id)"> model: @car.model year: @car.registration_year </p>
}
}
@code{
[Parameter]
public EventCallback<string> CarSelected { get; set; }
async Task onSelectCar(string e) {
await CarSelected.InvokeAsync(e);
}
//ReponseCarsJSON = ... json stuff to fetch Cars API
}
My question is how do I retrieve this data on parent, for example:我的问题是如何在父母身上检索这些数据,例如:
<Cars CarSelected="@getCarId"> </Cars>
@code {
private void getCarId () {
// get car id here
}
}
Simply pass it as a parameter to your getCarId
method.只需将其作为参数传递给您的
getCarId
方法。 ie: IE:
@code {
private void getCarId(string carId) {
// use carId here
}
}
One thing I like to do to avoid any potential errors is to make sure there's actually a callback delegate registered.为了避免任何潜在的错误,我喜欢做的一件事是确保实际上注册了一个回调委托。 So I do:
所以我这样做:
private async Task onSelectCar(string e) {
if (CarSelected.HasDelegate) {
await CarSelected.InvokeAsync(e);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.