以编程方式填写reactjs表单 [英] Programmatically fill reactjs form

查看:191
本文介绍了以编程方式填写reactjs表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个用户脚本,但我无法设法填写reactjs制作的表格.我的代码:

I am writing an userscript and I can't manage to fill a form made by reactjs. My code:

document.querySelector("#id-username").value = "name@domain.xx";
// Attempt to notify framework using input event
document.querySelector("#id-username").dispatchEvent(new Event("input", {data:"name@domain.xx"}));
// Attempt to notify framework using change event
document.querySelector("#id-username").dispatchEvent(new Event("change"));
// This doesn't help either
document.querySelector("#id-username").dispatchEvent(new Event("blur"));
// Submit the form using button (it's AJAX form)
document.querySelector("fieldset div.wrap button").click();

加载页面后,我将此代码输入了开发人员工具控制台.但是,该表格忽略了我的编程输入:

I entered this code into developper tools console after loading the page. However the form ignores my programatical input:

可以在此处找到该表格.我工作的目的是自动登录到给定的网站.我提供了特定的URL,但是我希望可以解决此问题的通用解决方案(例如,使用一些reactjs API)可以应用于任何reactjs表单.其他用户可能需要此解决方案来为其站点编写自动测试.

The form can be found here. The purpose of my work is to automate login to given website. I provided the specific URL, but I expect generic solution to this problem (eg. using some reactjs API) that can be applied to any reactjs form. Other users might need this solution for writing automated tests for their sites.

推荐答案

必须向ReactJS发出事件以使其注册值.特别是input事件.确保事件冒泡非常重要-React JS在document级别上只有一个侦听器,而不是在输入字段上.我精心设计了以下方法来设置输入字段元素的值:

Event must be emmited to ReactJS to make it register the value. In particular, the input event. It is really important to ensure that the event bubbles - React JS has only one listener at the document level, rather than on the input field. I crafted the following method to set the value for input field element:

function reactJSSetValue(elm, value) {
    elm.value = value;
    elm.defaultValue = value;
    elm.dispatchEvent(new Event("input", {bubbles: true, target: elm, data: value}));
}

这篇关于以编程方式填写reactjs表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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