通过javascript在Blazor中更改输入值不会更改其绑定属性值 [英] Changing an Input value in Blazor by javascript doesn't change it's binded property value

查看:140
本文介绍了通过javascript在Blazor中更改输入值不会更改其绑定属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building a website using app.net 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中更改输入值不会更改其绑定属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆