简体   繁体   English

当我折叠、添加或删除面板时,React-hook-form 字段值会丢失

[英]React-hook-form field value get lost when i collapse, add or delete panel

I am using material ui ExpansionPanel.我正在使用材质 ui 扩展面板。 I am trying to add new panels from Add button click and remove panel from Remove button click, its working fine, problem is, when i expand, collapse, add or remove panels, form fields value get lost.我正在尝试从添加按钮单击添加新面板并从删除按钮单击删除面板,它工作正常,问题是,当我展开、折叠、添加或删除面板时,表单字段值会丢失。 I think it happens due to re-rendering or refresh.我认为这是由于重新渲染或刷新而发生的。

Let me know how can we implement above feature so that user can easly navigate to any panel add some detail from there and move to another panel and add some detail there, but while adding details from one to another panel, value must be there if user again goes to that perticular panel.让我知道我们如何实现上述功能,以便用户可以轻松导航到任何面板从那里添加一些细节并移动到另一个面板并在那里添加一些细节,但是在将细节从一个面板添加到另一个面板时,如果用户必须存在价值再次进入那个特定的面板。

Have a look on below sample code看看下面的示例代码

https://codesandbox.io/s/dhananajayx-3n73x?file=/src/App.js:146-160 https://codesandbox.io/s/dhananajayx-3n73x?file=/src/App.js:146-160

Any effort is highly appreciated任何努力都受到高度赞赏

useForm({ shouldUnregister: false }); useForm({ shouldUnregister: false });

When working with react-hook-form and each form element is rendered on a tab change or so, use the above code to not let any field unregister from the form and keep the form values as it is.当使用 react-hook-form 并且每个表单元素都在选项卡更改时呈现,使用上面的代码不要让任何字段从表单中注销并保持表单值不变。

  1. Send a ref to component(read Register fields for more information)向组件发送参考(阅读注册字段以获取更多信息)
  2. Set the defaultValue with previous value.使用以前的值设置 defaultValue。 in each re-render component uses default value in its input.在每个重新渲染组件中,在其输入中使用默认值。

look at this at codesandbox.看看这个在代码沙盒。

React Hook Form automatically removes value when input removes from the DOM tree, basically unregister is invoked when your inputs get collapsed.当输入从 DOM 树中删除时,React Hook Form 会自动删除值,基本上当你的输入折叠时会调用unregister

Solution解决方案

useEffect(() => {
  register('yourInput');
}, [register])


setValue('yourInput', 'data')

This unregister will not happen automatically and you can drive when to invoke unregister .unregister不会自动发生,您可以决定何时调用unregister

This works:这有效:

In the Main view:在主视图中:

const methods = useForm(form)
const [value, setValue] = useState(0)

<FormProvider {...{value, ...methods}}>

</FormProvider>

Example Tab Items:示例选项卡项:

// first item 
const TabItem1 = () => {
    const {value} = useFormContext()

    return <TabPanel {...{value, index: 0}}>
      {/*{Content here}*/}
    </TabPanel>
}

export default TabItem1

// second item
const TabItem2 = () => {
    const {value} = useFormContext()

    return <TabPanel {...{value, index: 1}}>
      {/*{content here}*/}
    </TabPanel>
}

export default TabItem2

And the TabPanel:和 TabPanel:

const TabPanel = ({children, value, index}) =>
    <div style={{display: value === index ? 'block' : 'none'}}>
        {children}
    </div>

export default TabPanel

I use stepper to enter user info divided to 4 steps & useForm({ shouldUnregister: false });我使用步进器输入用户信息,分为 4 个步骤 & useForm({ shouldUnregister: false }); didn't work so I Changed this:没用所以我改变了这个:

 {activeStep === 0 && (
            <label>
              Name:
              <input type="text" name="name"  />
            </label>
          )}

to:至:

 <label>
            Name:
            <input
              type="text"
              name="name"
              style={{ display: activeStep === 0 ? "block" : "none" }}
            />
 </label>

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

相关问题 使用React-hook-form的useFieldArray点击append怎么会出现空字段? - How can I get an empty field when I click on the append using the useFieldArray of React-hook-form? 为什么在 react-hook-form 中对动态表单使用 useFieldArray() 时不能关注当前字段? - Why can't I focus on the current field when using useFieldArray() for dynamic form in react-hook-form? 使用 react-hook-form 在 React 中编写另一个输入字段时重置一个输入字段 - Reset an input field when another one is written in React with react-hook-form 提交后 react-hook-form 字段刷新 - react-hook-form field refreshes after submit 以 react-hook-form 记录不断变化的输入字段? - Record a changing input field in react-hook-form? React-hook-form conditional required validation based on other field - React-hook-form conditional required validation based on other field 如何将句柄更改添加到此代码以进行验证。(我使用过 react-hook-form) - How to add handlechange to this code for Validation .(i have used react-hook-form) 在 react-hook-form 中设置 DatePicker 的值(来自 antd) - Setting the value of DatePicker (from antd) in react-hook-form react-hook-form 检查一个值是否包含在数组中 - react-hook-form check if a value is included in an array 无法获得 react-hook-form 以正确验证 email - Cannot get react-hook-form to validate an email properly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM