【问题标题】:React Material-UI Popper - popper ref doesn't workReact Material-UI Popper - popper ref 不起作用
【发布时间】:2021-02-23 05:04:22
【问题描述】:

我正在尝试实现当弹出器打开并且底部超过窗口底部时,它的位置将发生变化(从“右”到“右端”)。

我想从 ref 获得底部位置,看看它是否通过底部。问题是,我尝试过的 ref.current 都是空的。

这些是我迄今为止尝试过的:

  1. 将 ref 对象传递给 Popper 组件 props ref 和 popperRef。 on useEffect current 为 null。
  2. 将 ref 对象传递给 popper 包装的 div。同样,在 useEffect 上,当前属性为 null。
  3. 将回调传递给 popper ref/popperRef-props,以及它包装的 div。挂载时不会调用 ref 回调。
  • 我确实注意到 useEffect 是在 popper 显示在屏幕上之前执行的。

Popper 组件 - 将回调传递给 ref 到包装的 div 的示例

const customPopper = ({
 popperRef = (popperElement) => {}
}) => {
  const useStyles = makeStyles({
    Popper: { ...popperStyle, ['z-index']: '9999' }
  })
  const styles = useStyles();

  return (
    <Popper
      className={styles.Popper}
      placement={placement}
      open={open}
      anchorEl={anchorEl}
    >
      <ClickAwayListener onClickAway={handleClickAway}>

        <div ref={popperRef}>

          <CalendarPopover
            className={st(classes[calendarPopoverClass], { isMobile })}
            isShown
            withArrow={false}
            title={title}
            onClose={handleCloseClick}
          >
            {children}
          </CalendarPopover>
        </div>
      </ClickAwayListener>
    </Popper >
  )

父组件引用处理程序

 const popperRefHandler = (popperRef: React.MutableRefObject<HTMLDivElement>) => {
    const popperBottom = popperRef.current.getBoundingClientRect().bottom;
    console.log('hello from popper mount in agenda cell, popper-bottom: ', popperBottom);

  }

编辑 1 - 沙盒示例

https://codesandbox.io/s/material-ui-issue-forked-zy11e?file=/src/index.js

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    它在传递回调时起作用。它传递的参数是 DOM 元素,并且没有 RefObject 中的当前属性:

    live example

    非常感谢 Material UI 团队的帮助:https://github.com/mui-org/material-ui/issues/23484

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-03
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 2022-08-15
      • 1970-01-01
      • 2021-06-01
      相关资源
      最近更新 更多