自动完成 Material-ui React getOptionSelected 道具不工作

AutoComplete Material-ui React getOptionSelected prop not working

我对反应还很陌生,非常感谢这里的一些指示:

我有一个带有特定选项集的自动完成下拉菜单。我希望根据我的条件默认选择其中之一。

据我所知,这可以通过 getOptionSelected prop 在自动完成中完成。

我创建了一个样本来测试它,但是它没有按预期工作。你能帮忙吗?

CodeSandbox Here

/* eslint-disable no-use-before-define */
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option: { title: string; year: number }) => option.title}
      getOptionSelected={(option) => option.year === 1994}
      style={{ width: 300 }}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 }
];

V5

如果您要更新到 v5,getOptionSelected 将重命名为 isOptionEqualToValue。请参阅迁移指南 here

V4

仅当您需要验证所选选项时才使用 getOptionSelected,这可能不是您想要的。

如果要根据条件更改选中的选项,可以修改Autocomplete组件的value属性。在下面的演示中,您可以通过在 TextField.

中指定选项索引来更改所选选项
export default function Demo() {
  // Use null instead of undefined to fix mixing uncontrolled and controlled error
  // https://github.com/mui-org/material-ui/issues/18173#issuecomment-552420187
  const [value, setValue] = React.useState(null);
  const onChangeOptionIndex = (e) => {
    const optionIndex = parseFloat(e.target.value);
    const selectedValue =
      top100Films.find((o, i) => i === optionIndex) || top100Films[0];

    setValue(selectedValue);
  };

  return (
    <Box display="flex">
      <TextField label="Option Index" onChange={onChangeOptionIndex} />
      <Autocomplete
        id="combo-box-demo"
        options={top100Films}
        onChange={(_, newValue) => setValue(newValue)}
        value={value}
        getOptionLabel={(option) => option.title}
        style={{ width: 300 }}
        renderInput={(params) => (
          <TextField {...params} label="Combo box" variant="outlined" />
        )}
      />
    </Box>
  );
}

现场演示