ReactJS + Material-UI自动完成默认值不起作用 [英] ReactJS + Material-UI Autocomplete defaultValue not working

查看:65
本文介绍了ReactJS + Material-UI自动完成默认值不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了

I followed the same pattern mentioned in this question but the difference is I'm passing the 'options' as 'props.CountryList' from another component. Can someone please let me know what are the changes I need to do when I pass the 'options' as a props ?

解决方案

You are passing an empty array as defaultValue value in your Controller - then you are using that as the value for Autocomplete. I also don't think you need the defaultValue in Autocomplete.

Anyways, the code below should work

export default function AutoSelect({ options, selectedValue }) {
  const { control, setValue } = useForm();

  if (options.length === 0) {
    return null;
  }

  const defaultValue = options.find((i) => i.value === selectedValue);

  return (
    <Controller
      render={(props) => (
        <Autocomplete
          options={options}
          getOptionLabel={(option) => option.label}
          value={props.value}
          onChange={(e, values) => setValue("food", values)}
          renderInput={(params) => (
            <TextField
              {...params}
              label="Choose food"
              name={props.name}
              placeholder="Choose food"
              variant="outlined"
              fullWidth
            />
          )}
        />
      )}
      control={control}
      name="food"
      defaultValue={defaultValue}
    />
  );
}

这篇关于ReactJS + Material-UI自动完成默认值不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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