简体   繁体   English

react.js使用javascript更改输入值

[英]react.js change input value with javascript

I would like to change the values with javascript/jquery but when I hit submit, the old initial values are used and not my new ones. 我想使用javascript / jquery更改值,但是当我点击Submit时,将使用旧的初始值,而不是新的初始值。

I cannot change the react code, I can only change the values with javascript/jquery as shown below. 我无法更改反应代码,只能使用javascript / jquery更改值,如下所示。

var value = "randomIntValue";
$("input[data-reactid='.0.2.0.0.0.0.0.2.0.0.3.0.3.0.0']").val(value).change();

The above code doesn't work! 上面的代码不起作用!

From what I can gather from the comments above, the problem you're having is that you're trying to change a React-controlled component through jQuery. 从上面的评论中我可以得出,您遇到的问题是您试图通过jQuery更改React控制的组件。

This is not possible because you cannot update the React state from the view directly. 这是不可能的,因为您不能直接从视图中更新React状态。 When you run your jQuery code, the changes are only temporarily applied to the DOM, but React does not know about this. 当您运行jQuery代码时,更改仅临时应用于DOM,但是React对此一无所知。 As such, when React needs to re-render the view the old values in the DOM will be overwritten. 这样,当React需要重新渲染视图时,DOM中的旧值将被覆盖。

Also, accessing the component via the data-reactid is a bad approach because the value is likely to change if any changes are made the React virtual-DOM. 而且,通过data-reactid访问组件是一种不好的方法,因为如果对React virtual-DOM进行了任何更改,则该值很可能会更改。

Using React and jQuery is usually a bad idea when trying to apply DOM changes. 在尝试应用DOM更改时,使用React和jQuery通常不是一个好主意。 If you cannot access/change any React code, I'm afraid you're out of luck. 如果您无法访问/更改任何React代码,恐怕您不走运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM