如何使用来自useEffect的事件调用函数

时间:2021-04-08 09:19:38

标签: reactjs typescript react-hooks use-effect

我有 <form>handleSubmit

如何使用 handleSubmit 中的 event 调用 useEffect 函数?

useEffect(() => {
    if (searchFromUrl) {
      handleSubmit();
    }
  }, []);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
}

<form onSubmit={handleSubmit} className="flex relative search-form"></form>

这是我的错误

 const handleSubmit: (e: React.FormEvent<HTMLFormElement>) => Promise<void>
    Expected 1 arguments, but got 0.ts(2554)
    SearchBox.tsx(27, 31): An argument for 'e' was not provided.

2 个答案:

答案 0 :(得分:3)

您在没有 handleSubmit(); 事件变量的情况下调用 e

如果您真的想在 useEffect 中调用它,请将 e 参数更改为可选:

const handleSubmit = async (e?: React.FormEvent<HTMLFormElement>) => {
  if (e) {
    e.preventDefault();
  }
  // do something
}

答案 1 :(得分:0)

useEffect(() => {
    if (searchFromUrl) {
      handleSubmit(e); // u need to provide 'e'
    }
}, []);

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
}

<form onSubmit={handleSubmit} className="flex relative search-form"></form>