【问题标题】:Tooltip delay on hover with RXJS使用 RXJS 悬停时的工具提示延迟
【发布时间】:2020-08-29 14:52:00
【问题描述】:

我正在尝试使用 rxjs(没有 setTimeout())添加工具提示延迟(300 毫秒强调文本)。我的目标是在 TooltipPopover 组件中包含这个逻辑,稍后将被重用,延迟将作为道具传递(如果需要)。

我不确定如何使用 rxjs 在 TooltipPopover 组件中添加“延迟”逻辑?

Portal.js

const Portal = ({ children }) => {
  const mount = document.getElementById("portal-root");
  const el = document.createElement("div");

  useEffect(() => {
    mount.appendChild(el);
    return () => mount.removeChild(el);
  }, [el, mount]);

  return createPortal(children, el);
};

export default Portal;

TooltipPopover.js

import React from "react";

const TooltipPopover = ({ delay??? }) => {

  return (
    <div className="ant-popover-title">Title</div>
    <div className="ant-popover-inner-content">{children}</div>
  );
};

App.js

const App = () => {

  return (
        <Portal>
          <TooltipPopover>
            <div>
              Content...
            </div>
          </TooltipPopover>
        </Portal>
  );
};

然后,我在不同的地方渲染 TooltipPopover:

ReactDOM.render(<TooltipPopover delay={1000}>
                        <SomeChildComponent/>
                </TooltipPopover>, rootEl)

【问题讨论】:

    标签: reactjs rxjs settimeout delay react-portal


    【解决方案1】:

    这是我的方法:

    mouseenter$.pipe(
      // by default, the tooltip is not shown
      startWith(CLOSE_TOOLTIP),
    
      switchMap(
        () => concat(timer(300), NEVER).pipe(
          mapTo(SHOW_TOOLTIP),
          takeUntil(mouseleave$),
          endWith(CLOSE_TOOLTIP),
        ),
      ),
    
      distinctUntilChanged(),
    )
    

    我对 React with RxJS 的最佳实践不是很熟悉,但这就是我的理由。所以,流程是这样的:

    • 在mouseenter$ 上,启动计时器。使用 concat(timer(300), NEVER) 是因为虽然 300 毫秒后应该显示工具提示,但我们只想在 mouseleave$ 发出时隐藏它。
    • 300ms 后,工具提示显示并将关闭mouseleave$
    • 如果mouseleave$ 在 300 毫秒过去之前发出,CLOSE_TOOLTIP 将发出,但您可以在 distinctUntilChanged 的帮助下避免(我认为)不必要的重新渲染

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      相关资源
      最近更新 更多