我有一个用于过滤搜索的子组件(DropdownFilter(,它接受建议列表的输入和更新该列表的函数。
由于某种原因,DropdownFilter.Suggestions
在最初设置后没有更新,我不知道如何再次更新。任何关于如何在最初绑定后更新属性的信息都将非常棒!
DropdownFilter.razor:
<input id="search" @onfocus="SearchFocused" @onblur="SearchUnfocused" @oninput="UpdateSearchText" />
@foreach (var suggestion in Suggestions)
{
<p>@suggestion</p>
}
@code {
[Parameter]
public Action<string> SearchFieldChanged { get; set; }
//[Parameter]
//public RenderFragment<TSuggestion> SuggestionTemplate { get; set; }
[Parameter]
public List<string> Suggestions { get; set; }
private bool searchFocus = false;
private void SearchFocused(FocusEventArgs args) {
searchFocus = true;
//UpdateSearchText();
}
private void SearchUnfocused(FocusEventArgs args) => searchFocus = false;
private void UpdateSearchText(ChangeEventArgs args)
{
SearchFieldChanged.Invoke((string)args.Value);
}
public void Refresh() {
StateHasChanged();
}
}
索引.razor:
@page "/example"
<div class="container-fluid dropdown-holder">
<DropdownFilter @ref="dropdown" Suggestions="@maskResults" SearchFieldChanged="UpdateSearchResults" />
</div>
@code {
DropdownFilter dropdown;
public class MaskResult {
public string name;
}
static readonly string[] allMasks = {
"Electric",
"Water",
"Ground",
"Fire",
"Bug"
};
public List<string> maskResults = allMasks.ToList();
private void UpdateSearchResults(string search)
{
search = search.ToLower();
maskResults = allMasks.Where((mask) =>
{
return mask.ToLower().StartsWith(search);
}).ToList();
dropdown.Refresh();
}
}
我认为您正在尝试创建一个Datalist
,请检查这个答案:"数据列表如何将所选项目绑定到对象
如果您在此处添加StateHasChanged((调用,它应该可以工作:
private void UpdateSearchResults(string search)
{
search = search.ToLower();
maskResults = allMasks.Where((mask) =>
{
return mask.ToLower().StartsWith(search);
}).ToList();
StateHasChanged(); // Add this line
dropdown.Refresh();
}
据我所知,如果手动更新组件的参数,在某些情况下,Blazor不会自动获得更新组件所需的信息。因此,如果您调用StateHasChanged,它将重新评估您进行调用的组件的子屏幕的所有参数。
如果我错了,我会让别人纠正我的。
谢谢并祝你好运:(