Blazor开发技术问询:如何获取按钮的innerText内容
在Blazor中获取按钮的innerText
错误写法说明
你提供的代码存在问题:直接在@onclick的lambda表达式中使用button.innerText是无效的,因为Blazor的组件模型不允许直接引用未定义的DOM元素变量。
正确实现方式
方式1:通过ElementReference + .NET内置API(.NET 7+ 推荐)
这种方式无需额外JS代码,适用于Blazor WebAssembly:
<p>点击的按钮文本:@StringClicked</p> <button type="submit" class="bu2ncon10" @ref="targetButton" @onclick="GetButtonInnerText">示例按钮</button> @code { private ElementReference targetButton; private string? StringClicked; private async Task GetButtonInnerText() { // .NET 7+ 直接调用GetPropertyAsync获取属性值 StringClicked = await targetButton.GetPropertyAsync<string>("innerText"); } }
方式2:ElementReference + JS互操作(兼容所有Blazor版本)
如果你的项目基于.NET 6及以下,或者需要兼容Blazor Server,可以使用JS互操作:
- 组件代码:
@inject IJSRuntime JSRuntime <p>点击的按钮文本:@StringClicked</p> <button type="submit" class="bu2ncon10" @ref="targetButton" @onclick="GetButtonInnerText">示例按钮</button> @code { private ElementReference targetButton; private string? StringClicked; private async Task GetButtonInnerText() { StringClicked = await JSRuntime.InvokeAsync<string>("getElementInnerText", targetButton); } }
- 在
wwwroot/index.html(WebAssembly)或Pages/_Host.cshtml(Server)中添加JS函数:
function getElementInnerText(element) { return element.innerText; }
方式3:直接绑定文本变量(更符合Blazor组件思想)
如果按钮文本本身是绑定到组件变量的,无需操作DOM,直接使用绑定的变量即可:
<p>点击的按钮文本:@StringClicked</p> <button type="submit" class="bu2ncon10" @onclick="() => StringClicked = ButtonText">@ButtonText</button> @code { private string ButtonText = "示例按钮"; private string? StringClicked; }
内容的提问来源于stack exchange,提问作者Razel Marquez Bigayan
相关产品推荐
相关产品推荐

