为何无法在Blazor Wasm的Razor文件中使用<script>标签?
Blazor Wasm中script标签函数未定义的问题解答
问题原因
- Blazor组件内的
<script>标签不会被浏览器常规解析执行,Blazor的组件渲染逻辑会过滤或延迟处理这类标签,导致你定义的adjustRows函数没有被挂载到全局window作用域中,触发oninput事件时自然找不到这个函数。 - 第二个文本框用的是内联JS代码,直接操作当前元素,不需要依赖全局函数,所以能正常生效。
解决办法
1. 使用全局脚本文件
把JS函数放到wwwroot/js目录下的自定义脚本文件(比如custom.js):
function adjustRows(textarea) { textarea.rows = 1; textarea.rows = Math.round(textarea.scrollHeight / textarea.clientHeight); }
然后在wwwroot/index.html中引入这个脚本:
<script src="js/custom.js"></script>
这样函数就会被注册到全局作用域,第一个文本框的oninput="adjustRows(this)"就能正常调用。
2. 用Blazor JS互操作注册全局函数
在组件中通过IJSRuntime将函数注册到全局:
@inject IJSRuntime JS <textarea rows="1" @oninput="() => JS.InvokeVoidAsync('adjustRows', textareaRef)"></textarea> @code { private ElementReference textareaRef; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { await JS.InvokeVoidAsync(@" window.adjustRows = function(textarea) { textarea.rows = 1; textarea.rows = Math.round(textarea.scrollHeight / textarea.clientHeight); } "); } } }
3. 纯Blazor方式处理
完全通过Blazor的事件绑定和JS互操作实现,不依赖原生事件属性:
<textarea rows="1" @bind="InputText" @oninput="AdjustRows" @ref="textareaRef"></textarea> @code { private string InputText { get; set; } private ElementReference textareaRef; private async Task AdjustRows() { await JS.InvokeVoidAsync(@" (textarea) => { textarea.rows = 1; textarea.rows = Math.round(textarea.scrollHeight / textarea.clientHeight); } ", textareaRef); } }
内容的提问来源于stack exchange,提问作者Flippowitsch
相关产品推荐
相关产品推荐

