React Hooks Form - 带有来自 useState 的数据的 onSubmit

React Hooks Form - onSubmit with data from useState

您好 :) 我想使用客户的地址数据创建结帐表单,但是在提交时我想附加存储在 useState (cartItems) 中的订单数据。现在,我已经完成了带有 console.log 仅形成输入的 onSubmit 按钮的反应挂钩形式。 最好的方法是什么?

const Checkout = ({ emoneyPayment, setEmoneyPayment, cartItems }: CheckoutProps) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Order>();

我不熟悉 React Hooks Form 和 TypeScript,但在 JS / React 中你可以将它包装在另一个钩子中:

const Checkout = ({ emoneyPayment, setEmoneyPayment, cartItems }: CheckoutProps) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Order>();

  const [cartItems, setCartItems] = useState([])

  // this function will be redefined every time cartItems or handleSubmit updates 
  const submitForm = useCallback(() => {
    handleSubmit(cartItems)
  }, [cartItems, handleSubmit])

  return <div onClick={submitForm}>Submit</div>
}

更新: 您还需要将 cartItems 传递给 handleSubmit。这似乎是这样做的方式:

const Checkout = ({ emoneyPayment, setEmoneyPayment, cartItems }: CheckoutProps) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Order>();

  const [cartItems, setCartItems] = useState([])

  const onSubmit = (data) => {
    const finalData = {...data, cartItems}
    alert(JSON.stringify(finalData));
    // do your actual submit stuff here
  };

  return <form onSubmit={handleSubmit(onSubmit)}>...formcomponents...</form>
}