在Blazor中的父组件中获取子组件绑定值

问题描述 投票:1回答:3

让Say Child Component称为cinput.cshtml

<input type="text" bind="@username">

@functions{
string username;
}

和父组件称为pform.cshtml

<cinput></cinput>
<input type="text" bind="@email">
<input type="button" onclick="@onsubmit">

@functions{

string email;

public void onsubmit(){
   //Call api
}
}

所以问题是如何在父组件中获取用户名值?

c# blazor
3个回答
1
投票

您应该执行以下操作:

  1. 在子组件中定义EventCallback委托属性:
[Parameter] protected  EventCallback<string>  OnUserNameChanged { get; set; }

此属性将包含父组件上定义的方法的委托。

  1. 在子组件中定义属性和支持变量:
    private string username;
    public string UserName
    {
        get => username;
        set
        {
            username = value;
            // Invoke the delegate passing it the changed value
            OnUserNameChanged?.Invoke(value);
        }
    } 
  1. 在父组件中定义一个方法,当用户名更改时,该方法将从子组件调用:
    public async void UserNameChanged(string username)
       {
          // Gets and consume the user name
       }
  1. 这是您的子组件在父组件中的使用方式:请注意,我们将方法名称分配给属性OnUserNameChanged,它是子组件中的委托属性
     <cinput OnUserNameChanged="UserNameChanged" ></cinput>
        <input type="text" bind="@email">
        <input type="button" onclick="@onsubmit">

希望这可以帮助...

这就是史蒂夫安德森对于ref所说的话:

用例

预期用例是允许父组件向子组件发出命令,例如“show”或“reset”。

即便如此,在架构上它也是一种折衷方案,因为对于你的子组件来说,无状态(即,不会对除参数以外的任何状态起作用)会更加清晰,在这种情况下,理论上它甚至不可能有意义发布除了改变孩子的参数之外的“动作”,在这种情况下你根本不需要参考。

强烈建议您不要将ref用作改变子组件状态的方法。相反,始终使用常规声明性参数将数据传递给子组件。这将导致子组件自动在正确的时间重新呈现。我们正在改变如何表示组件上的参数,以便默认情况下它们是封装的,不可能从外部读/写。


-1
投票

你直接要求的是像ref参数。 afaik不支持。

当你想要撰写表格时,它可能是这样的:

1)为项目添加一个可变类型。 System.String是不可变的,所以我们需要:

public class StringWrapper
{
    public string Value { get; set; }
}

2)将其作为参数添加到cinput:

<input type="text" bind="@username.Value" />    
@functions{    
    [Parameter]
    StringWrapper username { get; set;  }    
}

3)然后顶层表单可以暴露一个cinput可以变异的包装器:

<cinput username="@userName"></cinput>

@functions{    
    StringWrapper userName = new StringWrapper { Value = "John Doe" };
    string email;

    public void onsubmit()
    {
        //Call api with userName.Value    
    }
}

-2
投票

所以我做了这样的事情

cinput.cshtml

<input type="text" bind="@username">

@functions{
string username;

string getUsername(){
 return username;
}

}

在pform.cshtml中

<cinput ref="_cinput"></cinput>
<input type="text" bind="@email">
<input type="button" onclick="@onsubmit">

@functions{

string email;
Cinput _cinput

public void onsubmit(){
   //get username
   string uname = _cinput.getUsername();
   //Call api

}
}

https://docs.microsoft.com/en-us/aspnet/core/razor-components/components?view=aspnetcore-3.0#capture-references-to-components

© www.soinside.com 2019 - 2024. All rights reserved.