我在作業中使用受控輸入元素,但我被卡住了。
基本上,我需要在表單中自動填充一些輸入元素,但問題是我需要以模擬用戶輸入(在本例中為鍵入)的方式填充它,以便觸發 onChange 函式的邏輯。所以,正因為如此。我需要模擬打字行為,而不僅僅是value為元素設定。
盡管搜索了以前的問題并閱讀了關于 的檔案KeyboardEvent,但我還是無法完成這項作業。
目前,我正在 Codesandbox 中進行試驗,只是為了讓事情變得更容易,但即使在這個簡單的環境中,我也無法讓它發揮作用。
這是代碼及其Codesandbox 鏈接
import { useRef, useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [state, setState] = useState();
const inputRef = useRef();
const event = new KeyboardEvent("keypress", { key: 99 });
useEffect(() => {
inputRef.current.dispatchEvent(event);
}, [inputRef]);
const onChange = (e) => {
setState(e.target.value);
};
return (
<div className="App">
<h1>{state}</h1>
<input
type="text"
id="name"
onChange={onChange}
ref={inputRef}
value={state}
/>
</div>
);
}
希望你們中的一個人可以幫我解決這個問題。
謝謝閱讀!
uj5u.com熱心網友回復:
相關評論:
我認為沒有必要調度一個keypress事件來運行你的特效邏輯。
例如,您可以使用useEffect僅在初始渲染時運行的a來觸發您想要的任何特殊邏輯——這樣您就可以擁有表單狀態的常規初始值。
import { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
// In the useState call, you can initialize the value.
const [state, setState] = useState("initial value");
const specialEffectFunction = () => {
// here's the code for the special effect you want to run on load
console.log('this is the special onChange effect')
}
useEffect(() => {
// This will trigger the special function which you want to run
// when the app loads
specialEffectFunction();
// if it really HAS to be the `onChange` function that's called,
// then you'll need to call that with a fake ChangeEvent.. but I don't
// think that should be necessary...
}, [])
const onChange = (e) => {
setState(e.target.value);
};
return (
<div className="App">
<h1>{state}</h1>
<input
type="text"
id="name"
onChange={onChange}
value={state}
/>
</div>
);
}
uj5u.com熱心網友回復:
我無法修復的問題Keyboard Event我沒有關于它的知識,但我希望我設法解決模仿人類的問題,使用自動填寫下面的代碼輸入。
function AutoFillInput({ finalValue }: { finalValue: string }) {
const [inputValue, setInputValue] = useState('');
const [sliceStart, setSliceStart] = useState(0);
const changeHandler = useCallback((event) => {
setInputValue(event.target.value);
}, []);
useEffect(function handleFinalValueChange() {
setInputValue('');
if (sliceStart < finalValue.length)
setSliceStart(x => x 1);
}, [finalValue]);
useEffect(function handleSlice() {
setInputValue(finalValue.slice(0, sliceStart));
if (sliceStart < finalValue.length) {
setTimeout(() => {
setSliceStart(x => x 1);
}, 800);
}
}, [sliceStart]);
return (
<input
value={inputValue}
onChange={changeHandler}
placeholder={'Auto fill input'}
/>
)
}
function App() {
return (
<div >
<AutoFillInput finalValue={'hello world'} />
</div>
);
}
export default App;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/318245.html
標籤:javascript 反应
