繁体   English   中英

react-hook-form(V7):如何通过 onChange 将 function 传递给嵌套的 Material UI 组件

[英]react-hook-form(V7): How to pass a function via onChange to a nested Material UI component

我有一个 Material UI 嵌套组件,如下所示:

imports . . . 

const TxtInput = ({ name, value, label, required }) => {
  const { control, ...rest } = useFormContext()
  return (
    <Controller
      name={name}
      defaultValue={value}
      control={control}
      render={({
        field: { onChange, onBlur, value, name, ref }
      }) =>
        <TextField
          required={required}
          fullWidth
          label={label}
          id={name}
          inputProps={{ 'aria-label': label }}
          onBlur={onBlur}
          onChange={onChange}
          checked={value}
          inputRef={ref}
          {...rest}
        />}
    />
  )
}

export default TxtInput

在我的 app.js 中, <TxtInput />看起来像这样:

<FormProvider {...methods}>
    <form onSubmit={handleSubmit(submit)}>
        <TxtInput
        name='fullName'
        label='First and last name'
        required
        value=''
        onChange={() => console.log('hello')}
    </form>
</FormProvider>

我希望在我的控制台中每次击键都会看到“你好”,但事实并非如此。

有谁知道为什么?

我想你想要的是将 onChange 事件传递给 TxtInput 而不是使用它自己的 Controller onChange

const TxtInput = ({ name, value, label, required, onChange }) => { // add onChange here
  const { control, ...rest } = useFormContext()
  return (
    <Controller
      name={name}
      defaultValue={value}
      control={control}
      render={({
        field: { onBlur, value, name, ref } // remove onChange here to allow pass though from parent onChange
      }) =>
        <TextField
          required={required}
          fullWidth
          label={label}
          id={name}
          inputProps={{ 'aria-label': label }}
          onBlur={onBlur}
          onChange={onChange}
          checked={value}
          inputRef={ref}
          {...rest}
        />}
    />
  )
}

制作一个代码框来模拟您的案例。 你可以检查一下

https://codesandbox.io/s/runtime-hill-9q2qu?file=/src/App.js

最后嵌套的 onChanged function 应返回为 ()=>onChangeFn

暂无
暂无

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

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