[英]react-hook-form(V7): How to pass a function via onChange to a nested Material UI component
I am have a Material UI nested component that look as follow:我有一个 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
While in my app.js, <TxtInput />
look like this:在我的 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>
And I am expecting to see 'Hello' with every keystroke in my console but, that is not the case.我希望在我的控制台中每次击键都会看到“你好”,但事实并非如此。
Does anyone know why?有谁知道为什么?
I think what you want is to pass the onChange event to the TxtInput instead of using its own Controller onChange我想你想要的是将 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}
/>}
/>
)
}
make a codesandbox to simulate your case as well.制作一个代码框来模拟您的案例。 You can check it out
你可以检查一下
https://codesandbox.io/s/runtime-hill-9q2qu?file=/src/App.jshttps://codesandbox.io/s/runtime-hill-9q2qu?file=/src/App.js
The last nested onChanged function should be returned as ()=>onChangeFn最后嵌套的 onChanged function 应返回为 ()=>onChangeFn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.