我试图理解数据绑定,但无法找到实现这一点的最佳方法。
我的组件很简单:
<button type="reset" class="btn btn-primary" @onclick="ResetValues">Reset values</button>
<br />
<div class="row">
@for(int i=1; i<=NumberOfContacts; i++)
{
<div class="col">
<input type="text" class="form-control input-md">
</div>
}
</div>
@code{
[Parameter]
public int NumberOfContacts {get; set;}
public void ResetValues()
{
// how to reset dynamically generated input field values
}
}
//In Index page, I am simply going:
<Contacts NumberOfContacts="3" />
它正确地生成了我定义的输入字段的数量(在参数内的索引页上(,但我如何绑定值,以便在重置按钮单击事件时读取并清除它们?
<button type="reset" class="btn btn-primary" @onclick="ResetValues">Reset values</button>
<br />
<div class="row">
@for(int i=0; i<NumberOfContacts; i++)
{
@* Never use the loop variable directly *@
int local=i;
@* Add a key to help Blazor track things *@
<div class="col bg-success" @key=local>
@* Bind to an array element *@
<input type="text" class="form-control input-md" @bind=contacts[local]>
</div>
}
</div>
@code{
[Parameter]
public int NumberOfContacts {get; set;}
// Bind this to the inputs
string[] contacts;
protected override void OnInitialized()
{
// Make sure to initialise the contacts array
ResetValues();
}
public void ResetValues()
{
contacts = new string[NumberOfContacts];
}
}