通过javascript在Blazor中更改输入值不会更改其绑定属性值

编程入门 行业动态 更新时间:2024-10-27 14:26:24
本文介绍了通过javascript在Blazor中更改输入值不会更改其绑定属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用app core 3.1和blazor来构建网站. 在我的组件之一中,我有:

I'm building a website using app core 3.1 with blazor. In one of my components I have :

<input @bind="Message" type="text" id="input-message"/>

Message只是一个字符串属性.

Message is just a string property.

并且我有javascript:

and I have javascript:

document.getElementById('input-message').value = 'some text';

问题是运行上述js后,<input>的值发生变化,但Message的值没有变化,当然,如果我在<input>内键入或粘贴某些内容,Message的值也会发生变化.

The problem is after running the above js, <input> value changes but Message value doesn't, and of course if I type or paste something inside <input> , Message value changes too.

推荐答案

通过JavaScript显然更改<input>值或DOM中的任何其他更改不会更改State,因此blazor不会重新呈现该组件.即使在剃须刀页面中手动调用StateHasChanged();也不起作用.

Apparently changing <input> value or any other changes in DOM by javascript doesn't change State, so blazor won't re-render the component. Even calling StateHasChanged(); manually in your razor page won't work.

要完成此操作,您只需触发与用户正常修改<input>时发生的相同DOM事件,如下所示:

To get this done, you just have to trigger the same DOM events that occur if the user modifies the <input> normally, just like below:

var myElement = document.getElementById('input-message'); myElement.value = 'some text'; var event = new Event('change'); myElement.dispatchEvent(event);

更多推荐

通过javascript在Blazor中更改输入值不会更改其绑定属性值

本文发布于:2023-10-25 22:30:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528302.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   属性   javascript   Blazor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!