首页 > 解决方案 > 为什么 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>
  );
}

希望你们中的一个人可以帮我解决这个问题。

谢谢阅读!

标签: javascriptreactjs

解决方案


相关评论:

我认为没有必要调度一个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>
  );
}

推荐阅读