在Material-UI中以编程方式打开工具提示 [英] Programmatically open Tooltip in Material-UI
问题描述
我需要能够在元素上添加一个工具提示,以便其功能像普通的一样(当元素悬停时会打开),同时我需要能够以编程方式打开它.
我知道它具有允许执行此操作的 open
道具,但是在这种情况下,我将组件从不受控制的状态切换为受控制的状态,这是不可能的.
我也无法在工具提示中的按钮上汇总:hover
事件,因为这在浏览器中是不可能的.
有没有可能通过裁判来做到这一点?当我在工具提示中使用ref时,它只会传递给子元素.
谢谢!
当控制 Tooltip
时,
I need to be able to add a tooltip to the element so it functions like normal (opens up when element is hovered) and at the same time I need an ability to open it up programmatically.
I know it has open
prop that allows to do so, but in this case I will be switching component from uncontrolled to controlled and this isn't possible.
I'm also unable to sumulate :hover
event on a button inside tooltip because this is impossible in browser.
Is there a way to accomplish this maybe thru refs? When I use ref with tooltip it just being passed over to the child element.
Thanks!
When the Tooltip
is controlled, the onOpen and onClose functions will still fire at the times when it would open/close the tooltip in the uncontrolled case. You can use these functions to change the controlled state of the Tooltip
.
Working example:
import React from "react";
import ReactDOM from "react-dom";
import Tooltip from "@material-ui/core/Tooltip";
import Button from "@material-ui/core/Button";
function App() {
const [tooltipIsOpen, setTooltipIsOpen] = React.useState(false);
return (
<div className="App">
<Tooltip
open={tooltipIsOpen}
onOpen={() => setTooltipIsOpen(true)}
onClose={() => setTooltipIsOpen(false)}
title="I'm a controlled tooltip"
>
<span>Hover over me or click the button</span>
</Tooltip>
<div style={{ marginTop: 50 }}>
<Button
onClick={() => setTooltipIsOpen(!tooltipIsOpen)}
variant="contained"
color="primary"
>
Click me to {tooltipIsOpen ? "close" : "open"} the tooltip
</Button>
</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
这篇关于在Material-UI中以编程方式打开工具提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!