简体   繁体   中英

React Hook Form - Smart Components - form broken when Inputs are wrapped in an element

Following the tutorial - https://www.react-hook-form.com/advanced-usage#SmartFormComponent ) - works until the inputs are wrapped in an element. What changes would one need to make to the Form component to make this work?

<Form onSubmit={(data) => setData(data)}>
    {/* wrapping the inputs breaks the form */}
    <div>
        <Input name="firstName" />
        <Input name="lastName" />
    </div>

    <button>Submit</button>
</Form>

A hacky way out of this problem would be to create something like:

const InputWithDiv = props => (
  <div>
    <Input {...props} />
  </div>
)

ref: https://stackoverflow.com/a/66215997/2102042

but this isn't a solution


👀 👉 example : https://codesandbox.io/s/react-hook-form-smart-form-component-forked-8o0f9?file=/src/index.js

I think you have to use FormContext here. There is also this discussion answered by the author of the library which recommends using FormContext for a scenario where your inputs are deeply nested. For example when using a <fieldset /> or a fragment or as in your case a <div /> .

编辑 React Hook 表单 - 智能表单组件(分叉)

Here is the relevant section from the docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM