以编程方式填写reactjs表单

Tom*_*ica 4 javascript greasemonkey userscripts reactjs

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

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();
Run Code Online (Sandbox Code Playgroud)

我在加载页面后将此代码输入到开发工具控制台中.然而,表格忽略了我的编程输入:

图片描述

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

Tom*_*ica 7

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

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


bsc*_*agg 5

对于Chrome版本64,有一种解决方法。否则,该事件将被忽略。

参见:https : //github.com/facebook/react/issues/10135#issuecomment-314441175

(在链接中对fatfisz表示了完全的功劳)

function setNativeValue(element, value) {
  const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
  const prototype = Object.getPrototypeOf(element);
  const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;

  if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(element, value);
  } else {
    valueSetter.call(element, value);
  }
}
Run Code Online (Sandbox Code Playgroud)

用法

setNativeValue(textarea, 'some text');
// you must dispatch the input event, or the value will not update !!!
textarea.dispatchEvent(new Event('input', { bubbles: true }));
Run Code Online (Sandbox Code Playgroud)