Реагирование на события дочерних элементов родительского компонента - PullRequest
0 голосов
/ 23 января 2019

У меня есть 2 компонента A и B, B, являющийся дочерним по отношению к A. Есть ли что-то вроде EventEmitter (Angular) в Blazor? Как я могу прикрепить обработчик событий к родительскому элементу, который может реагировать на вывод его дочернего элемента?

Дети

<button onclick="Emit">Press me</button>
@functions(){
[Parameter] // i do not know how the `Output` is called
private string Pressed {get;set;}
public void Emit()
{
  //somehow emit `Pressed` to the parent , make him respond
}
}

Родительский компонент

<Child [Pressed]="doSomething"> </Child>
@functions{
 doSomething(string value){
  Console.WriteLine("Child sent me : "+value);
 }
}

P.S Извините за синтаксические ошибки, я новичок в Blazor.

Ответы [ 2 ]

0 голосов
/ 23 января 2019

Компонент A.cshtml

// Define a method in the parent component which will be called 
// from the child component when the user tap the button residing 
// in the child component. This method has a string parameter passed
// from the child component
public void GetValueFromChild(string value)
 {
        // Do somethig with value
  } 

Компонент B.cshtml


// When the user click the button the method GetValueFromChild
// defined on the parent component is called

<button class="btn" onclick=@(() => OnAddValue("some string value"))>Add</button>

    @functions
{
    // Define an Action delegate property which stores a reference
    // to A.GetValueFromChild
    // Parameters
    [Parameter] Action<string> OnAddValue{ get; set; }
}

A.cshtml

// Here (in the parent component) you place the child component and
// set its OnAddValue to the name of the method to be called
<B OnAddValue = "GetValueFromChild"></B> 

Пожалуйста, отметьте мой ответ как принятыйесли это помогло вам
Надеюсь, это поможет ...

0 голосов
/ 23 января 2019

Вы можете использовать параметр Action

<button onclick="Emit">Press me</button>
@functions(){
[Parameter] protected Action<string> Pressed {get;set;}

public void Emit()
{
  Pressed?.Invoke("Some String");
}
}

В Emit вы используете условное выражение для проверки того, подписан ли кто-либо на действие, и вызываете его, передавая параметры.

Не забудьте, что в Parent, если вы хотите обновить страницу, вызовите StateHasChanged () в методе "doSomething".

...