【问题标题】:Is there a way to reuse Bootstrap's OverlayTrigger component?有没有办法重用 Bootstrap 的 OverlayTrigger 组件?
【发布时间】:2022-01-19 22:55:37
【问题描述】:
【问题讨论】:
标签:
reactjs
performance
optimization
bootstrap-4
react-bootstrap
【解决方案1】:
如果您能够使用Overlay 而不是OverlayTrigger,您可以通过将事件处理程序添加到要触发覆盖的组件(例如onClick、onMouseOver/onMouseOut)来实现。事件处理程序将:
- 将触发器更新为触发叠加的元素(因此叠加显示在元素旁边)
- 更新
show 状态以确保显示叠加层
HTML 将允许您定义一个可被多个对象(在本例中为 4 个按钮)使用的单个 Overlay 元素:
<div>
<Overlay target={target.current} show={show} placement="right">
<Tooltip id="button-tooltip">Simple tooltip</Tooltip>
</Overlay>
<Button onMouseOver={showOverlay} onMouseOut={showOverlay}>
Test
</Button>
<Button onMouseOver={showOverlay} onMouseOut={showOverlay}>
Test 2
</Button>
<Button onMouseOver={showOverlay} onMouseOut={showOverlay}>
Test 3
</Button>
<Button onMouseOver={showOverlay} onMouseOut={showOverlay}>
Test 4
</Button>
</div>
需要引入show 状态和target ref:
const [show, setShow] = useState(false); // Used to display the overlay
const target = useRef(null); // Used to store the reference to the HTML element that triggered the overlay
showOverlay 函数会将目标引用设置为被单击/悬停的 HTML 元素,然后设置标志以显示叠加层:
const showOverlay = (e) => {
target.current = e.target;
setShow(!show);
};
有这个here 的工作演示。