javascript - 为什么 KeyboardEvent 不能在反应中使用此 Input 元素?
问题描述
我在工作中使用受控输入元素,但我被卡住了。
基本上,我需要在表单中自动填充一些输入元素,但问题是我需要以模拟用户输入(在本例中为键入)的方式填充它,以触发 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>
);
}
希望你们中的一个人可以帮我解决这个问题。
谢谢阅读!
解决方案
相关评论:
我认为没有必要调度一个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>
);
}
推荐阅读
- machine-learning - 在 LSTM 中,应该在训练集和测试集分割之前还是之后进行归一化?
- python - (Python) 为变量分配特定字符在多维数组中出现的次数
- sql - 替换 SQL 中的值
- python - TensorFlow GPU 在 Python 2.7 的 multiprocessing.Process 调用分叉的新进程中不可用
- python - Msys2 升级中断 python2-pyqt5
- laravel - 无法通过 Laravel Backpack 中的方法覆盖订单
- node.js - 使用强大/快速时文件不写入磁盘
- javascript - 无法使选择过滤器 JavaScript?
- javascript - 无法使用 Google 的 node.js 客户端库生成 JWT 客户端。运行代码时出现 Typeerror
- javascript - 将图像从一个文件夹复制/移动到另一个文件夹