【React hack】在React中模拟触发输入
11月11日11月22日

在 React 中进行模拟触发输入

参考:facebook/react#11488

在自动化测试或在线调试React项目中,会遇到直接修改input的valut值UI变化,但是内部state并没有修改的情况。因此需要hack方法来解决:

1let input = document.querySelector('xxx'); 2let lastValue = input.value; 3input.value = 'xxx'; 4let event = new Event('input', {bubbles: true}); 5event.simulated = true; 6let tracker = input._valueTracker; 7if (tracker) { 8 tracker.setValue(lastValue) 9} 10input.dispatchEvent(event); 11const enterKeyEvent = new KeyboardEvent('keypress', { 12 key: 'Enter', 13 keyCode: 13, 14 code: 'Enter', 15 which: 13, 16 bubbles: true, 17}); 18input.dispatchEvent(enterKeyEvent);
1const fileInput = document.querySelector('input[type="file"]'); 2 3async function simulateRemoteFileSelection(url) { 4 const response = await fetch(url); 5 const blob = await response.blob(); 6 7 const file = new File([blob], "file.mp4", { 8 type: blob.type, 9 }); 10 11 const dataTransfer = new DataTransfer(); 12 dataTransfer.items.add(file); 13 14 fileInput.files = dataTransfer.files; 15 16 const event = new Event('change', {bubbles: true}); 17 fileInput.dispatchEvent(event); 18} 19 20simulateRemoteFileSelection('xxxx');

cd ..
©2024All rights reserved by z0ffyPowered by Gossip.