简体   繁体   English

将自定义道具/方法注入到`handleSubmit` 的方法?

[英]Way to inject custom props/methods to `handleSubmit`?

I'm using react hook form , and I'm looking for a way to inject custom props to the handleSubmit method returned by the hook.我正在使用react hook form ,并且我正在寻找一种方法将自定义道具注入由钩子返回的handleSubmit方法。 The reason I need to do this is my component acts as a Consumer for a state library , and I want to update the state after submitting the form.我需要这样做的原因是我的组件充当状态库Consumer ,我想在提交表单后更新状态。 I may also want to pass props to the method.我可能还想将道具传递给方法。

From looking at the API, it seems like this isn't possible.从 API 来看,这似乎是不可能的。 Any thoughts on a workaround or how to do this?关于解决方法或如何执行此操作的任何想法?

I don't use this library, but it seems that getValues function returned from useForm hook opens the way to synchronize Your component state with form data stored in the "react-hook-form":我不使用这个库,但似乎从useForm钩子返回的getValues函数打开了将组件状态与存储在“react-hook-form”中的表单数据同步的方法:

docs文档

import React, { useMemo, useEffect, useState } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, getValues } = useForm();
  const [ valuesState, setValuesState ] = useState();

  const values = useMemo(() => getValues());

  useEffect(() => setValuesState(values), [values]);

  return (
    <form>
      [...]
    </form>
  );
}

why not just update the state during handleSubmit ?为什么不在handleSubmit期间更新状态?

export default function App() {
  const { register, getValues } = useForm();
  const onSubmit = data => {
    // do your state update here update(data)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      [...]
    </form>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应中的handleSubmit()内没有this.props - no this.props inside handleSubmit() in react 我的this.props在handleSubmit和其他函数上未定义 - My this.props are undefined on handleSubmit and other function 反应类型错误:this.props.handleSubmit 不是 function - React TypeError: this.props.handleSubmit is not a function React-hook-form:递归注入 props 到嵌套的自定义字段 - React-hook-form: recursively inject props to nested custom fields 将自定义数据属性注入到 REACT `props.children` - Inject custom data attribute to REACT `props.children` ESlint抱怨在prop验证中缺少this.props.handleSubmit - ESlint complains about this.props.handleSubmit missing in prop validation withFormik如何在handleSubmit中访问包装表单的道具 - withFormik how to access wrapped form's props in handleSubmit 如何注入React Component道具? - How to inject into React Component props? 有没有办法编写一个可以接受 Chakra UI 样式道具的自定义 React 组件? - Is there a way to write a custom React component that will accept Chakra UI style props? Uncaught TypeError:无法读取handleChange处未定义的属性“ setState”,无法读取handleSubmit处为null的属性“ props” - Uncaught TypeError: Cannot read property 'setState' of undefined at handleChange , Cannot read property 'props' of null at handleSubmit
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM