reactjs - MUI 自动完成(多个)控制值 - 神秘的输入行为

标签 reactjs material-ui

我正在尝试编写代码以在键盘输入时异步搜索多选组合。

但是我在最新版本(5.2.2)中发现了一个我无法解释的奇怪行为。我提炼出以下问题(基于 MUI 自动完成页面的示例):

import * as React from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

const options = [
  { label: "Option 1", value: 1 },
  { label: "Option 2", value: 2 }
];

export default function ControllableStates() {
  // const [value, setValue] = React.useState<any | null>([]);
  const value = [];
  const [inputValue, setInputValue] = React.useState("");

  console.log("Current Value:", value);

  return (
    <div>
      <div>{`value: ${value !== null ? `'${value}'` : "null"}`}</div>
      <div>{`inputValue: '${inputValue}'`}</div>
      <br />
      <Autocomplete
        multiple={true}
        value={value}
        onChange={(event: any, newValue: any | null) => {
          //setValue(newValue);
        }}
        inputValue={inputValue}
        onInputChange={(event, newInputValue) => {
          setInputValue(newInputValue);
        }}
        id="controllable-states-demo"
        options={options}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Controllable" />}
      />
    </div>
  );
}


codeSandbox如下:https://codesandbox.io/s/controllablestates-material-demo-forked-ygqp2?file=/demo.tsx

如果您在 codeSandbox 中尝试,您将无法在 TextField 字段中输入任何内容。

但是,如果您切换评论:

  const [value, setValue] = React.useState<any | null>([]);
  // const value = [];

您将能够在 TextField 字段中输入内容。这里到底发生了什么?该值根本没有改变。

任何人都可以弄清楚为什么我的第一个代码(其中值是 const 空数组)不起作用?

我问的原因是我需要将(受控)值作为 props 传入,然后如果它为 null,则将其设置为默认值 []。我发现由于这种默认设置,我无法在 TextField 中输入内容。

最佳答案

如果您使用react-hook-form,您可以使用设置自动完成

  • multiple 添加多个值,
  • 选项:您添加要选择的选项
  • getOptionLabel:显示选项标签
  • onChange:使用react-hook-form的onChange函数设置选定的值
  • renderInput:渲染输入
import { useForm, Controller } from 'react-hook-form'
import {
  Box,
  TextField,
  Autocomplete,
} from '@mui/material'

const {
  ...
  control,
  formState: { errors },
} = useForm()

<Box mt={2}>
  <Controller
    control={control}
    name="industries"
    rules={{
      required: 'Veuillez choisir une réponse',
    }}
    render={({ field: { onChange } }) => (
      <Autocomplete
        defaultValue={
          useCasesData?.industries
            ? JSON.parse(useCasesData?.industries)
            : []
        }
        multiple
        disableCloseOnSelect
        options={companyIndustryTypes}
        getOptionLabel={(option) => option.name}
        onChange={(event, values) => {
          onChange(values)
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            label="Type d'industries"
            placeholder="Type d'industries"
            helperText={errors.industries?.message}
            error={!!errors.industries}
          />
        )}
      />
    )}
  />
</Box>

Note that options in my case companyIndustryTypes is an array of object :

[
    {
        id: 1,
        name: "Accounting",
    },
    {
        id: 2,
        name: "Administration & Office Support",
    },
    ...
]

enter image description here

关于reactjs - MUI 自动完成(多个)控制值 - 神秘的输入行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70193775/

相关文章:

javascript - Material-UI 更改抽屉颜色

javascript - 在 React.js 中使用 onKeyPress 而不是 onKeyUp 检测何时按下删除或退格键

javascript - ReactJS 和 Material UI makeStyles/useStyles 问题

javascript - 如何根据 Material UI (React JS) 中的要求制作一个 'Select' 组件

javascript - React InstantSearch RefinementList transformItems 不工作

reactjs - Material-ui Typography with router link always underlined

reactjs - 如何在reactjs中的material-UI多选框中将对象列表设置为默认值?

javascript - React js 组件, map 有效,foreach 无效

javascript - 如何在React中使用可变数据和实时图表实现最佳性能?

javascript - 如何从 html-webpack-plugin 生成的 index.html 中排除 bundle.css?