在通过React-Hook-Forms更改值之后,如何触发MUI的Textfield的rerender?

发布于 2025-02-07 20:39:32 字数 2621 浏览 2 评论 0原文

我使用Mitalui Textfields渲染一种表格。我使用react-hook-form来控制它,并提供最初空白的defaultValues

对API进行查询以获取用户的帐户数据,因此defaultValues在初始表单呈现后进行更新。

在我的表单处理程序中,我使用使用 reset()带有新填充的数据的表单(这也是从API收到更新的数据后完成的。

这可以正常工作,除非初始DefaultValues为空白。当它们被填充时,该值将进入...但是标签不会向上移动,并且占位符并未删除。

如果初始数据为空白:

​conil.png“ rel =” nofollow noreferrer“>

仅在我手动之后编辑字段进行标签的表现:

ref不这样做?

代码:

import React, { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import * as Yup from 'yup'

import { yupResolver } from '@hookform/resolvers/yup'
import Button from '@material-ui/core/Button'
import BaseTextField from '@material-ui/core/TextField'

// Example form schema
const schema = Yup.object().shape({
  firstName: Yup.string(),
})

/* A thin wrapper around MUI textField to convert the name of ref
 * prop to `innerRef`, to make MUI match with react-hook-form's register pattern
 */
// eslint-disable-next-line react/display-name
const TextField = React.forwardRef((props, ref) => (
  <BaseTextField {...props} inputRef={ref} />
))

/**
 * An adapter interfacing between react-query's mutate() function and react-hook-form
 */
const MyForm = ({ data, mutate, submitting }) => {
  const { register, handleSubmit, reset } = useForm({
    defaultValues: data,
    resolver: schema ? yupResolver(schema) : undefined,
  })

  // Reset the form values if new data is received (e.g. from API refresh or from
  // the initial GET query)
  // TODO If using this with MUI outlined text fields that were previously blank,
  // This won't cause the label to shift up. What a bum bum.
  useEffect(() => {
    reset(data)
  }, [reset, data])

  return (
    <form onSubmit={handleSubmit(mutate)}>
      <TextField
        disabled={submitting}
        fullWidth
        id="firstName"
        label="First Name"
        margin="normal"
        variant="outlined"
        // NOTE my TextField is already adapted to forward `ref` from spreading register
        {...register('firstName')}
      />
      <Button
        variant="contained"
        disabled={submitting}
        color="primary"
        type="submit"
      >
        Save
      </Button>
    </form>
  )
}

I render a form using MaterialUI TextFields. I use react-hook-form to control it, and provide defaultValues which are initially blank.

A query is made to the API for a user's account data, and thus the defaultValues get updated after the initial form render.

In my form handler I use useEffect to reset() the form with the newly populated data (this is also done on receipt of updated data from the API).

This works correctly, except in the case where the initial defaultValues are blank. When they get populated, the value gets entered... but the label isn't moved upward, and the placeholder isn't removed.

If the initial data is blank:

enter image description here

Then after the data updates:

enter image description here

Only after I manually edit the field does the label behave:

enter image description here

The Question

How can I trigger a rerender in the textFields to get them to understand they need to move the label, since RHF setting their values via the ref doesn't do that?

The Code:

import React, { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import * as Yup from 'yup'

import { yupResolver } from '@hookform/resolvers/yup'
import Button from '@material-ui/core/Button'
import BaseTextField from '@material-ui/core/TextField'

// Example form schema
const schema = Yup.object().shape({
  firstName: Yup.string(),
})

/* A thin wrapper around MUI textField to convert the name of ref
 * prop to `innerRef`, to make MUI match with react-hook-form's register pattern
 */
// eslint-disable-next-line react/display-name
const TextField = React.forwardRef((props, ref) => (
  <BaseTextField {...props} inputRef={ref} />
))

/**
 * An adapter interfacing between react-query's mutate() function and react-hook-form
 */
const MyForm = ({ data, mutate, submitting }) => {
  const { register, handleSubmit, reset } = useForm({
    defaultValues: data,
    resolver: schema ? yupResolver(schema) : undefined,
  })

  // Reset the form values if new data is received (e.g. from API refresh or from
  // the initial GET query)
  // TODO If using this with MUI outlined text fields that were previously blank,
  // This won't cause the label to shift up. What a bum bum.
  useEffect(() => {
    reset(data)
  }, [reset, data])

  return (
    <form onSubmit={handleSubmit(mutate)}>
      <TextField
        disabled={submitting}
        fullWidth
        id="firstName"
        label="First Name"
        margin="normal"
        variant="outlined"
        // NOTE my TextField is already adapted to forward `ref` from spreading register
        {...register('firstName')}
      />
      <Button
        variant="contained"
        disabled={submitting}
        color="primary"
        type="submit"
      >
        Save
      </Button>
    </form>
  )
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文