Blazor 自动将 Textarea 滚动到底部

Blazor auto scroll Textarea to bottom

我如何在 Blazor 中将 TextArea 的值每次更改时自动滚动到底部?

为了测试它,我尝试使用内联 JS 来更改我在 Stack Overflow 上找到的元素的大小: " oninput="this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';" "

只要我手动填充 TextArea,它就可以工作。但是当我想从后端填充它时它不起作用:

        protected async System.Threading.Tasks.Task TestButtonClick0()
        {
            TextAreaText += ">> SPAM Test \n";
        }

有几种方法可以自动滚动文本区域。然而,它可能无法使用内联 JavaScript 完成,因为像“onchange”和“oninput”这样的事件是由用户操作触发的。因此,在以编程方式更新 textarea 值时,您需要调用 JavaScript 函数来执行此操作。最简单的方法是添加一个 JavaScript 函数,例如:

function scrollToEnd(textarea) {
    textarea.scrollTop = textarea.scrollHeight;
}

然后从 Blazor 页面调用它:

@page "/"
@using Microsoft.JSInterop
@inject IJSRuntime JS

@functions{
    ElementReference TextAreaRef;

    string TextAreaText = "Example auto-scroll\n";

    void ScrollToEnd() {
        JS.InvokeVoidAsync("scrollToEnd", new object[] {TextAreaRef});
    }   
}

<button class="btn btn-primary m-2" @onclick="ScrollToEnd">Add Line</button>
<br/>
<textarea @ref=TextAreaRef value="@TextAreaText" class="form-control" rows="5"></textarea>

有关工作示例,请参阅此 Blazor Fiddle:

https://blazorfiddle.com/s/3ioprd8b