当与react-hook-form的控制器一起使用时,MUI Autocomplete的'defaultValue'不起作用 [英] MUI Autocomplete's 'defaultValue' not working when used with Controller of react-hook-form

查看:108
本文介绍了当与react-hook-form的控制器一起使用时,MUI Autocomplete的'defaultValue'不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将MUI的自动完成功能与react-hook-form一起使用.我已经在React Hook Form的Controller中包装了一个自动完成组件.当我尝试将defaultValue设置为AutoComplete时,它不起作用,当我尝试更改预设值时,自动完成组件会中断.这是我的代码段.

 <控制器name ="combo-box-demo";control = {control}defaultValue = {top100Films.find(film => film.year === selectedFilmYear)}as = {<自动完成id ="combo-box-demo";options = {top100Films}getOptionLabel = {option =>option.title}样式= {{宽度:300}}renderInput = {params =>(< TextField {... params} label =组合框";变体=概述的"./>)}/>}/> 

正在运行的演示代码的沙箱链接位于

I am trying to use MUI's Autocomplete with react-hook-form. I have wrapped an Autocomplete component in React Hook Form's Controller. When I try to set defaultValue to AutoComplete it does not work, when I try to change the preset value the Autocomplete component breaks. Here is the snippet from my code.

<Controller
  name="combo-box-demo"
  control={control}
  defaultValue={top100Films.find(film => film.year === selectedFilmYear)}
  as={
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  }
/>

Sandbox link of working demo code is here.

解决方案

You should add an onChange prop on the Controller and return the selected object value

Also you can then implement getOptionSelected AutoComplete

export default function ComboBox() {
  const { control } = useForm({});
  const [selectedFilmYear, setSelectedFilmYear] = React.useState(1994);
  return (
    <Controller
      name="combo-box-demo"
      control={control}
      defaultValue={top100Films.find(film => film.year === selectedFilmYear)}
      onChange={([val, obj]) => obj}
      as={
        <Autocomplete
          id="combo-box-demo"
          options={top100Films}
          getOptionSelected={(obj, newval) => obj.name === newval.name}
          getOptionLabel={option => option.title}
          style={{ width: 300 }}
          renderInput={params => (
            <TextField {...params} label="Combo box" variant="outlined" />
          )}
        />
      }
    />
  );
}

这篇关于当与react-hook-form的控制器一起使用时,MUI Autocomplete的'defaultValue'不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆