reactjs - Autocomplete Material-UI 中如何默认打开下拉列表?

标签 reactjs material-ui

在自动完成表单中,显示国家数据及其相关代码。当输入文本获得焦点时,将填充下拉列表。我的意图是在没有焦点要求的情况下预加载数据数组。例子见代码

const [newValue, setNewValue] = useState(null);
const [textToggle, textToggleState] = useState(false);

render(
         <div
          style={{ cursor: "pointer" }}
          onClick={() => {
            textToggleState(!textToggle);
          }}
        >
          <h5>+{newValue == null ? "91" : newValue.calling_code}</h5>
        </div>
        {textToggle ? (
          <Autocomplete
            id="size-small-standard"
            size="small"
            options={cities}
            onChange={(event, value) => {
              setNewValue(value);
              textToggleState(!textToggle);
            }}
            autoSelect={true}
            getOptionLabel={(option) =>
              `${option.country}` + `+ ${option.calling_code}`
            }
            renderOption={(option) => (
              <>{`${option.country} + ${option.calling_code}`}</>
            )}
            //defaultValue={cities[98]}
            style={{ width: "100%" }}
            renderInput={(params) => (
              <TextField
                {...params}
                variant="standard"
                placeholder="Search your country"
                style={{ width: "40%" }}
              />
            )}
          />
        ) : (
          ""
        )}
  </div>
)

在这里您可以看到数据显示在输入文本焦点上。什么可能是最好的解决方案 预加载数据?

CodeSandbox 链接:https://codesandbox.io/s/how-to-add-only-single-value-from-autocomplete-in-material-ui-forked-tu218

最佳答案

只需控制 Autocompleteopen 状态并将默认值设置为 true:

export default function ComboBox() {
  // default value to true to open at first render
  const [open, setOpen] = useState(true);

  return (
    <Autocomplete
      open={open}
      onOpen={() => setOpen(true)}
      onClose={() => setOpen(false)}
      options={top100Films}
      getOptionLabel={(option) => option.title}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

现场演示

Edit 67043434/how-to-pre-load-the-drop-down-list-in-autocomplete-material-ui

关于reactjs - Autocomplete Material-UI 中如何默认打开下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67043434/

相关文章:

material-ui - 如何从 Material ui 列表项中删除默认填充?

css - Material UI 列表中的 NO WRAP 挑战,ListItemText

reactjs - ListView 中的 TouchableOpacity 需要点击 2 次才能实现 onPress

node.js - 如何从nodejs接收reactjs上的cookie

reactjs - 在 SSR 上 react 水合作用

reactjs - 用于现场离开的 Material UI TextField 事件

reactjs - 如何改变material-ui对话框的位置?

html - Material-UI makeStyles 与 withStyles 生成的类名

javascript - 当使用 React 的 material-ui Appbar 上存在多个菜单时,如何分配打开 onClick 的 MenuItem?

javascript - 用 Typescript 编写的 React 应用程序中的错误参数类型