react.js change input value with javascript

一曲冷凌霜 提交于 2019-12-06 10:51:12

问题


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.

I cannot change the react code, I can only change the values with javascript/jquery as shown below.

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!


回答1:


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.

This is not possible because you cannot update the React state from the view directly. When you run your jQuery code, the changes are only temporarily applied to the DOM, but React does not know about this. As such, when React needs to re-render the view the old values in the DOM will be overwritten.

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.

Using React and jQuery is usually a bad idea when trying to apply DOM changes. If you cannot access/change any React code, I'm afraid you're out of luck.



来源:https://stackoverflow.com/questions/37937379/react-js-change-input-value-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!