You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Bootstrap Popover在可滚动容器滚动时不跟随按钮如何解决?

问题根因

你给OverlayTrigger传入的container={this}是错误用法,React-Bootstrap v0.33版本的container属性要求接收真实DOM节点或返回DOM节点的函数,传入组件实例无法被正确识别,导致Popover默认挂载在document.body下,和你的自定义滚动容器不属于同一个定位上下文,滚动时自然无法跟随触发按钮对齐。另外你的滚动容器未设置position: relative,即使传入正确的容器节点,Popover的绝对定位也找不到正确的相对锚点,也会导致偏移。

修复方案

第一步:给滚动容器添加ref,传入正确的container属性

修改App.js代码如下:

import "./styles.css";
import {
  Popover,
  OverlayTrigger,
  Button,
  ButtonToolbar
} from "react-bootstrap";
import React from "react";
import "bootstrap/dist/css/bootstrap.css";

const popoverBottom = (
  <Popover id="popover-positioned-scrolling-bottom" title="Popover bottom">
    <strong>Holy guacamole!</strong> Check this info.
  </Popover>
);

const popoverRight = (
  <Popover id="popover-positioned-scrolling-right" title="Popover right">
    <strong>Holy guacamole!</strong> Check this info.
  </Popover>
);

export default class Positioner extends React.Component {
  constructor(props) {
    super(props);
    // 给滚动容器创建ref
    this.scrollContainer = React.createRef();
  }

  render() {
    return (
      <div className="bs-example-popover-scroll" ref={this.scrollContainer}>
        <ButtonToolbar style={{ padding: "100px 0" }}>
          <OverlayTrigger
            // 传入滚动容器的真实DOM节点
            container={this.scrollContainer.current}
            trigger="click"
            placement="bottom"
            overlay={popoverBottom}
          >
            <Button>Bottom guacamole!</Button>
          </OverlayTrigger>
          <OverlayTrigger
            container={this.scrollContainer.current}
            trigger="click"
            placement="right"
            overlay={popoverRight}
          >
            <Button>Right guacamole!</Button>
          </OverlayTrigger>
        </ButtonToolbar>
      </div>
    );
  }
}

如果初始化时出现容器不存在的报错,可将container属性改为函数形式,会在Popover渲染时动态获取容器节点:
container={() => this.scrollContainer.current}

第二步:给滚动容器添加相对定位

修改styles.css中滚动容器的样式,新增position: relative:

.App {
  font-family: sans-serif;
  text-align: center;
}

.bs-example-popover-scroll {
  background: grey;
  padding: 20px;
  height: 200px;
  overflow: scroll;
  border: 1px solid black;
  position: relative; /* 新增这行 */
}

可选补充

如果滚动时仍偶现微小偏移,可获取OverlayTrigger的ref,监听滚动容器的scroll事件,手动调用实例的updatePosition方法重新计算Popover位置即可。

内容的提问来源于stack exchange,提问作者madebymt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:45:02