我在 Chrome 扩展上工作,我需要根据从 CSV 读取的数字来更新使用 React 制作的 html 页面的大量输入。我无法更新网站。
- 从呈现的网站复制的输入示例:
<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
})
}
}
- 每次更改输入值时,都会调用一个函数并进行 POST 来保存它。
在更改输入值以触发 POST 后,我想从扩展程序中触发 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
请问有什么想法吗?
最佳答案
你不能直接从它渲染的 DOM 元素调用 React 组件的方法。您需要触发一个冒泡的事件,以便 React 可以在 document
处捕获它。正常水平并处理它,就像处理真实的一样。
✨ Document.execCommand():
正如 @woxxom 在评论中指出的,最简单的方法可能是集中输入,然后使用 Document.execCommand()
:
const input1 = document.getElementById('input1');
const input2 = document.getElementById('input2');
input1.focus();
document.execCommand('insertText', false, 'input1');
input2.focus();
document.execCommand('insertText', false, 'input2');
<input id="input1" />
<input id="input2" />
⚒️手动调度事件:
否则,您可以手动尝试 dispatching a change
, input
and/or blur
event使用Event() constructor在您更改这些字段的值后。
此外,请注意 Event()
的第二个可选参数包含一个字段 bubbles
,默认情况下为 false
。 您需要该结果为true
。否则,这将不起作用,因为 React 正在监听 document
上的事件。 .
此外,您可能需要使用 Element.setAttribute()
同样,因为这将更新 DOM 上的 value
属性(字段上的初始值),而 element.value
将更新当前值(以及显示值) )。但通常情况下,这是不需要的。有关更多信息,请参阅What is the difference between properties and attributes in HTML? .
此方法可能存在一些计时问题,您可能需要使用 setTimeout
来处理当更新多个输入时,因此如果第一个有效,我会选择那个。
const input1 = document.getElementById('input1');
// This updates the value displayed on the input, but not the DOM (you can do that with setAttribute,
// but it's not needed here):
input1.value = 'input1';
// Dispatch an "input" event. In some cases, "change" would also work:
input1.dispatchEvent(new Event('input', { bubbles: true }));
// It looks like only one field will be updated if both events are dispatched
// straight away, so you could use a setTimeout here:
setTimeout(() => {
const input2 = document.getElementById('input2');
input2.value = 'input2';
input2.dispatchEvent(new Event('input', { bubbles: true }));
});
<input id="input1" />
<input id="input2" />
关于reactjs - 更改通过 Chrome 扩展进行 react 的输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54137836/