【问题标题】:React MUI: Autocomplete being used as Popover - Popper component misplacedReact MUI:自动完成被用作 Popover - Popper 组件错位
【发布时间】:2023-02-07 18:46:26
【问题描述】:

我想做什么

我正在尝试实现包含 TextInput 元素的控件,该元素在单击时打开 Popover,其中嵌入了 Autocomplete。当我点击TextInput 时,我试图将焦点放在建议列表(AutocompletePopper 元素)上。

为什么我需要它就是这样(或者至少这是我们的客户想要的)

我的代码是什么我的代码的简化版本在这里

import "./styles.css";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import Popper from "@mui/material/Popper";

import { createRef, useCallback, useState } from "react";
import Popover from "@mui/material/Popover";

export default function App() {
  const [anchorEl, setAnchorEl] = useState<HTMLDivElement | null>(null);
  const textFieldRef = createRef<HTMLDivElement>();

  const handleClick = useCallback(() => {
    setAnchorEl(textFieldRef.current);
  }, [textFieldRef]);

  const handleClose = useCallback(() => {
    setAnchorEl(null);
  }, []);
  const open = Boolean(anchorEl);

  return (
    <>
      <TextField id='textfield' ref={textFieldRef} onClick={handleClick} fullWidth />
      <Popover
        id='popover'
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        disablePortal
        anchorOrigin={{
          vertical: 54,
          horizontal: 0
        }}
      >
        <Autocomplete
          id='autocomplete'

          openOnFocus
          options={["abc"]}
          freeSolo
          multiple
          fullWidth
          value={[""]}
          PopperComponent={(props) => <Popper {...props} anchorEl={anchorEl}/>}
          renderOption={(props, option) => (
            <Box component="li" {...props}>
              {option}
            </Box>
          )}
          renderInput={(params) => (
            <TextField
              {...params}
              autoFocus
              InputProps={{
                ...params.InputProps
              }}
            />
          )}
        />
      </Popover>
    </>
  );
}

问题是什么Poppover 错位了焦点,如下所示

当我点击Autocomplete(或通常重新渲染屏幕)时,它会自行更正

为什么会发生(我的猜测是)Autocomplete 渲染有延迟,Popper 第一次渲染时没有锚点。我可以通过放置条件语句(例如

{ document.getElementById('popover`) && <Autocomplete ...

我的解决方案是什么我尝试了很多东西(我很刻薄许多).我能做的最好的就是使用

<Autocomplete...
PopperComponent={(props) => <Popper {...props}
              anchorEl={document.getElementById('textfield')
    modifiers={[
                {
                  name: 'offset',
                  options: { offset: [32.5, 58], },
                },
              ]}/>...

有两个问题 - 一个 - 它非常丑陋,两个 - 如果我添加更多条目,Autocomplete 框会变大,我需要以某种方式相应地调整偏移量(更丑陋)

非常感谢任何建议~

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    我觉得 getElementById 是异步的/显示为同步,不要将它用作 arg,在带有空 arg 的 useEffect 中使用它并在组件中设置它的值。

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 2021-10-23
      • 2022-11-30
      • 2015-10-26
      • 2019-10-07
      • 2022-01-25
      • 2021-03-20
      • 2022-12-25
      相关资源
      最近更新 更多