Blazor:同一页面多实例TextArea组件的不同结果如何在父组件获取?
实现父组件获取多个自定义TextArea组件的输入值
方案一:双向绑定参数(推荐)
这种方式符合Blazor组件交互规范,父组件通过绑定变量直接同步子组件的输入值。
1. 改造子组件TextArea
修改子组件代码,将内部输入值改为可双向绑定的参数,同时修复多实例ID冲突问题:
@inject IJSRuntime JsRuntime @inject NavigationManager NavManager <table width="100%"> <tr> <td> <table width="100%"> <tr> <td> <button @onclick="MakeBold">put bold</button> </td> </tr> </table> </td> </tr> <tr> <td> <textarea class="custom-textarea" id="@_uniqueId" @bind="Result" placeholder="Deutsche Beschreibung" rows="5"></textarea> </td> </tr> </table> <button @onclick="Finish">finish</button> @code { // 生成唯一ID避免多实例冲突 private readonly string _uniqueId = Guid.NewGuid().ToString(); // 双向绑定参数,父组件可直接绑定 [Parameter] public string Result { get; set; } = string.Empty; [Parameter] public EventCallback<string> ResultChanged { get; set; } private async Task MakeBold() { await JsRuntime.InvokeVoidAsync("makeBold", _uniqueId); } private void Finish() { // 子组件触发值更新时手动调用回调 ResultChanged.InvokeAsync(Result); } }
配套JS逻辑(需全局或组件内引入):
function makeBold(textareaId) { const textarea = document.getElementById(textareaId); if (!textarea) return; const start = textarea.selectionStart; const end = textarea.selectionEnd; const selectedText = textarea.value.substring(start, end); textarea.value = textarea.value.substring(0, start) + `<b>${selectedText}</b>` + textarea.value.substring(end); // 触发Blazor绑定更新 textarea.dispatchEvent(new Event('input')); }
2. 父组件绑定并获取值
父组件定义三个变量分别绑定每个TextArea,直接访问变量即可得到输入值:
<TextArea @bind-Result="@textArea1Value" /> <TextArea @bind-Result="@textArea2Value" /> <TextArea @bind-Result="@textArea3Value" /> <button @onclick="CollectAllResults">获取所有结果</button> @code { private string textArea1Value = string.Empty; private string textArea2Value = string.Empty; private string textArea3Value = string.Empty; private void CollectAllResults() { // 直接获取三个文本框的输入结果 Console.WriteLine($"文本框1:{textArea1Value}"); Console.WriteLine($"文本框2:{textArea2Value}"); Console.WriteLine($"文本框3:{textArea3Value}"); // 此处添加业务逻辑 } }
方案二:组件引用主动获取值
如果需要在特定时机主动从子组件取值,可通过组件引用调用子组件的公开方法。
1. 子组件添加公开方法
在TextArea的@code中添加获取当前值的方法:
public string GetCurrentInputValue() { return Result; }
2. 父组件通过引用取值
父组件声明子组件引用实例,调用方法获取值:
<TextArea @ref="textAreaRef1" /> <TextArea @ref="textAreaRef2" /> <TextArea @ref="textAreaRef3" /> <button @onclick="FetchAllResults">获取所有结果</button> @code { private TextArea? textAreaRef1; private TextArea? textAreaRef2; private TextArea? textAreaRef3; private void FetchAllResults() { if (textAreaRef1 != null && textAreaRef2 != null && textAreaRef3 != null) { var result1 = textAreaRef1.GetCurrentInputValue(); var result2 = textAreaRef2.GetCurrentInputValue(); var result3 = textAreaRef3.GetCurrentInputValue(); // 处理结果逻辑 } } }
注意事项
- 必须移除子组件中固定的
id="custom-textarea",否则多实例会出现ID冲突,导致JS操作错误。 - 通过JS直接修改textarea的value后,需手动触发
input事件,才能让Blazor双向绑定同步更新值。
内容的提问来源于stack exchange,提问作者innom
相关产品推荐
相关产品推荐

