代码之家  ›  专栏  ›  技术社区  ›  AlainIb

使用来自chrome扩展的react更改输入值

  •  1
  • AlainIb  · 技术社区  · 7 年前

    我在Chrome扩展上工作,我需要更新一个HTML页面的许多输入,这些输入是用从csv中读取的数字react生成的。我无法更新网站。

    - 从呈现的网站复制的输入示例:

      <td><input class="input input_small fpInput" value="29,4"></td>
    

    - 它是如何制作的(不确定100%的内容,必须阅读经过修改的JS源代码)

    {
        key: "render",
        value: function () {
            return s.a.createElement("input", {
                className: "input input_small fpInput",
                value: this.state.value,
                onChange: this.handleChange,
                onBlur: this.handleSubmit,
                onFocus: this.handleFocus
            })
        }
    }
    

    - 每次更改输入值时,都会调用一个函数,并进行一个日志来保存它。

    我想触发 onBlur() onChange() 在我更改了输入值以触发日志之后,从我的扩展

    我试过这个:

    var el = document. ... .querySelector('input'); // the selector is simplied of course
    el.value = 321;
    el.onChange();  // ERROR onChange is not a function
    el.onchange();  // ERROR onchange is not a function
    el.handleChange(); // ERROR handleChange is not a function
    

    有什么想法吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Michiel Dral    7 年前

    更详细地阐述@varoons的答案,这实际上是正确的,尽管解释有点简短。

    您可以通过将事件注入(以浏览器的方式调度)到DOM中来实现这一点:

    // Needs setAttribute to work well with React and everything, just `.value` doesn't cut it
    // Also changed it to a string, as all attributes are strings (even for <input type="number" />)
    el.setAttribute("value", "321"); 
    
    // As @wOxxOm pointed out, we need to pass `{ bubbles: true }` to the options,
    // as React listens on the document element and not the individual input elements
    el.dispatchEvent(new Event("change", { bubbles: true }));
    el.dispatchEvent(new Event("blur", { bubbles: true }));
    

    这实际上会调用所有的监听器,甚至是那些使用react(就像您的去污代码中的情况一样);或者使用简单的 element.onChange = () => {...} 听众。

    例子: https://codesandbox.io/s/kml7m2nn4r

        2
  •  0
  •   varoons    7 年前
    el.dispatchEvent(new CustomEvent("change"))