【问题标题】:How can I access function in ChildComponent from another ChildComponent in .NET Blazor如何从 .NET Blazor 中的另一个 ChildComponent 访问 ChildComponent 中的函数
【发布时间】:2020-01-17 06:45:45
【问题描述】:

我已经通过谷歌查看,只找到了解决方案,当您可以从孩子到父母以及其他方式而不是从孩子到孩子时获得函数/值。

父组件,子组件的容器

 //PARENT 
<h3>ParentComponent</h3>
<Child_1_Component></Child_1_Component>

<Child_2_Component></Child_2_Component>

<h3>Child_1_Component</h3>

CHILD 1 用户放入东西

//CHILD 1
<h1>User puts in something</h1>
<input type="text"/>
<button @onclick="@(() => getValue(10))"></button>

@code {
    List<WhatEver> whatEvers = new List<WhatEver>();

    public void getValue(int value)
    {
        var message = "something";
        for (int i = 0; i < value; i++)
        {
            var whatever = new WhatEver();
            whatever.Name = message;
            whatEvers.Add(whatever);
        }
        //Sends value to Service
    }
}

CHILD 2 通过服务显示用户在 Child 1 中输入的内容,并让用户可以更改值。

在这里我希望能够达到孩子 1 中的功能

<h3>Child_2_Component</h3>
<h1>Displays Value from service and lets user put in new value</h1>
<input type="text" />
<button @onclick="@(() => getValue(10))"></button>

@*Here I want to use the funcction getValue(x) in Child_1_Component*@

【问题讨论】:

    标签: .net blazor


    【解决方案1】:

    定义一个Worker类并将getValue(int value)放入。

    public class Worker{
        public object getValue(int value){
           //[...]
           return something;
        }
    }
    

    那么有两种可能:

    解决方案 1

    在两个子项的父项中创建一个 Worker 实例,并将其放到两个子项中。

    //PARENT 
    <h3>ParentComponent</h3>
    <Child_1_Component Worker="@MyWorker"></Child_1_Component>
    <Child_2_Component Worker="@MyWorker"></Child_2_Component>
    
    <h3>Child_1_Component</h3>
    
    @code {
        private Worker MyWorker{ get; set; }
    
        protected override void OnInitialized()
        {
           MyWorker = new Worker();   
        }
    }
    

    然后是 Child,其中 Worker 在两个孩子中都是同一个对象:

    //CHILD 1
    <h1>User puts in something</h1>
    <input type="text"/>
    <button @onclick="@(() => Worker.getValue(10))"></button>
    
    @code {
        [Parameter]
        public Worker Worker { get; set; }        
    }
    

    解决方案 2:

    您将 getValue(int value) 移动到一个 Service 中并在 Startup.cs 中定义它,然后两个孩子也有相同的实例。

     //Startup.cs
     public void ConfigureServices(IServiceCollection services)
     {
        [...]
        services.AddScoped<Worker>();
     }
    

    然后是 Child,其中 Worker 在两者中都是相同的对象:

    //CHILD 1
    @inject Worker MyWorker
    <h1>User puts in something</h1>
    <input type="text"/>
    <button @onclick="@(() => MyWorker.getValue(10))"></button>
    

    【讨论】:

      猜你喜欢
      • 2021-10-09
      • 1970-01-01
      • 2019-01-03
      • 2021-03-03
      • 2016-10-18
      • 2019-03-10
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多