Javascript 中的“event”已被弃用,我无法使用“preventDefault()”

Fat*_*lam 5 javascript forms event-handling dom-events preventdefault

我正在尝试使用该event.preventDefault()方法,但不断收到错误。它说已event弃用

我正在制作 Firebase 注册表单,我想阻止该表单提交。

这是完整的代码。

import React from "react"
import styled from "styled-components"
import getFirebase from "../../firebase"
import useInput from "./useInput"

const SignUpForm = () => {
  const firebaseInstance = getFirebase()
  const email = useInput("")
  const password = useInput("")

  const signUp = async () => {
        event.preventDefault()
    try {
      if (firebaseInstance) {
        const user = await firebaseInstance
          .auth()
          .createUserWithEmailAndPassword(email.value, password.value)
        console.log("user", user)
        alert(`Welcome ${email.value}!`)
      }
    } catch (error) {
      console.log("error", error)
      alert(error.message)
    }
  }
event.preventDefault()
  return (
    <FormWrapper onSubmit={() => signUp()}>
      <Title>Sign up</Title>
      <Input placeholder="Email" {...email} />
      <Input placeholder="Password" type="password" {...password} />
      <Button type="submit">Sign up</Button>
    </FormWrapper>
  )
}

export default SignUpForm

Run Code Online (Sandbox Code Playgroud)

以及useInput代码:

import { useState } from "react"

const useInput = initialValue => {
  const [value, setValue] = useState(initialValue)

  const handleChange = event => {
    setValue(event.target.value)
  }

  return {
    value,
    onChange: handleChange,
  }
}

export default useInput
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 4

该警告意味着全局变量 window.event已被弃用。您仍然可以访问与事件处理程序关联的事件,只需以正确的方式进行操作 - 通过使用处理程序回调中的参数。

改变

<FormWrapper onSubmit={() => signUp()}>
Run Code Online (Sandbox Code Playgroud)

<FormWrapper onSubmit={signUp}>
Run Code Online (Sandbox Code Playgroud)

然后 的signUp第一个参数将是事件,您将能够使用它并preventDefault在尝试时调用它。

const signUp = async (event) => {
Run Code Online (Sandbox Code Playgroud)

但不要放入event.preventDefault()功能组件的主体 - 也就是说,它不应该放在这里:

event.preventDefault()
  return (
    ...
Run Code Online (Sandbox Code Playgroud)

仅将其放入signUp处理程序中。