Loading... > 来自:https://codingdict.com/questions/77442 **对于React 16和React > = 15.6** 设置`.value=`器无法正常工作,因为React库会覆盖输入值设置器,但是我们可以直接在`input`as上下文中调用该函数。 ``` var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set; nativeInputValueSetter.call(input, 'react 16 value'); var ev2 = new Event('input', { bubbles: true}); input.dispatchEvent(ev2); ``` 对于textarea元素,你应该使用`prototype`的`HTMLTextAreaElement`类。 新的[codepen示例](https://codepen.io/catthr/pen/pddWzo)。 所有学分[这个贡献者](https://github.com/cypress-io/cypress/issues/647#issuecomment-335829482)和[他的解决方案](https://github.com/cypress-io/cypress/commit/4a56ca83b3b6e19ec57d10a8160f54f513e8f8ec) **仅适用于React <= 15.5的过时答案** 有了`react-dom ^15.6.0`您可以使用`simulated`标志事件对象的事件经过 ``` var ev = new Event('input', { bubbles: true}); ev.simulated = true; element.value = 'Something new'; element.dispatchEvent(ev); ``` 我[用一个例子](https://codepen.io/catthr/pen/PKXzLQ)做了一个[codepen](https://codepen.io/catthr/pen/PKXzLQ) 为了理解为什么需要新标记,我发现[此注释](https://github.com/cypress-io/cypress/issues/536#issuecomment-308739206)非常有帮助: > 现在,React中的输入逻辑对重复事件的重复事件进行重复数据删除,因此每个值不会触发多次。它侦听浏览器的onChange / > onInput事件以及DOM节点值prop上的设置(当您通过javascript更新值时)。这具有副作用,即如果您手动更新输入的值,则input.value > =’foo’然后使用{target:input}分派一个ChangeEvent React将同时注册集合和事件,看到它的值仍然是’‘foo > ‘,将其视为重复事件并吞下。 > > 在正常情况下,这可以正常工作,因为浏览器启动的“真实”事件不会触发element.value上的设置。您可以通过使用模拟标志标记触发的事件来暗中逃避此逻辑,并且反应将始终触发该事件。 > [](https://github.com/jquense/react/blob/9a93af4411a8e880bbc05392ccf2b195c97502d1/src/renderers/dom/client/eventPlugins/ChangeEventPlugin.js#L128)[https://github.com/jquense/react/blob/9a93af4411a8e880bbc05392ccf2b195c97502d1/src/renderers/dom/client/eventPlugins/ChangeEventPlugin.js#L128](https://github.com/jquense/react/blob/9a93af4411a8e880bbc05392ccf2b195c97502d1/src/renderers/dom/client/eventPlugins/ChangeEventPlugin.js#L128) 最后修改:2021 年 10 月 09 日 05 : 46 PM © 允许规范转载 赞赏 要多恰饭才能长胖 赞赏作者 支付宝微信