React:手动触发输入组件合成变化事件

Lit*_*lee 5 reactjs

我正在尝试使用以下命令构建一个带有清晰按钮的输入组件react@17

import { useRef } from 'react';

const InputWithClear = props => {
  const inputRef = useRef();
  return (
    <div>
      <input
        ref={inputRef}
        {...props}
      />
      <button
        onClick={() => {
          inputRef.current.value = '';
          inputRef.current.dispatchEvent(
            new Event('change', { bubbles: true })
          );
        }}
      >
        clear
      </button>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

使用此组件,例如:

<InputWithClear value={value} onChange={(e) => {
  console.log(e); // I want to get a synthetic event object here
}} />
Run Code Online (Sandbox Code Playgroud)

但清除按钮仅在我先输入任何内容时才起作用一次,然后再次停止工作。

如果我先输入一些内容然后单击清除按钮,则不起作用。

为什么不使用?

<InputWithClear value={value} onChange={(e) => {
  console.log(e); // I want to get a synthetic event object here
}} />
Run Code Online (Sandbox Code Playgroud)

因为合成事件对象将会丢失

那么,如何手动触发反应输入组件的合成更改事件?

buz*_*tto 0

您应该使用状态来控制输入值而不是创建 useRef,这就是正确的方法。你可以使用一个stopPropagationprop 来控制它:

const InputWithClear = ({value, setValue, stopPropagation = false}) => {

  const onClick = (e) => {
    if(stopPropagation)  e.stopPropagation()
    setValue('')
  }

  return (
    <div>
      <input
        value={value}
        onChange={e => setValue(e.target.value)}
      />
      <button
        onClick={onClick}
      >
        clear
      </button>
    </div>
  );
};

export default function App() {
  const [value, setValue] = useState('')
  return (
    <div className="App">
      <InputWithClear value={value} setValue={setValue} stopPropagation />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)